473,770 Members | 1,901 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Best way to return newly created object

Hi all,

Sometimes I have a function which creates an object and returns it.
Some are sets, other vectors but that's not very important. In these
cases I do something like this:

vector<int> * f() {
vector<int> * v = new vector<int>;
return v;
}

Would there be any other way without pointers?

Would this work:
vector<int>& f() {
vector<int> v;
return v;
}

???

Cheers,

Paulo Matos

Jul 23 '05 #1
29 2249
Geo


pmatos wrote:
Hi all,

Sometimes I have a function which creates an object and returns it.
Some are sets, other vectors but that's not very important. In these
cases I do something like this:

vector<int> * f() {
vector<int> * v = new vector<int>;
return v;
}

Would there be any other way without pointers?

Would this work:
vector<int>& f() {
vector<int> v;
return v;
}

???

Cheers,

Paulo Matos


No, that won't work, 'v' will be destroyed when 'f' returns, you will
have an invalid reference. You should consider returning a
std::auto_ptr, or some other smart pointer.

Jul 23 '05 #2
pmatos wrote:
Hi all,

Sometimes I have a function which creates an object and returns it.
Some are sets, other vectors but that's not very important. In these
cases I do something like this:

vector<int> * f() {
vector<int> * v = new vector<int>;
return v;
}

Would there be any other way without pointers?

Would this work:
vector<int>& f() {
vector<int> v;
return v;
}


No. Never return a reference to a local object.

What you could do is turn it around. Let the function take the vector as
parameter and fill it:

void f(vector<int>& vec)
{
//fill vec
}

Jul 23 '05 #3
"pmatos" <po**@sat.ine sc-id.pt> schrieb:
vector<int> * f() {
vector<int> * v = new vector<int>;
return v;
}


I suggest not to return a newly created object. Nobody knows what to
do with the pointer. How it is created? Do we have to delete it? Is it
a pointer on the heap or just an address of an existing object?

Indeed if the function and its caller don't use the same heap
management it could result in a serious problem. This is the case if
you create an object in a DLL and return a pointer up to an
application. If both modules are linked with a static runtime library
the application cannot delete the pointer.

I suggest to create the object outside the function. You can use the
function to fill it.

void f (vector<int>& v)
{
// fill v ...
}

T.M.
Jul 23 '05 #4

"pmatos" <po**@sat.ine sc-id.pt> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
Hi all,

Sometimes I have a function which creates an object and returns it.
Some are sets, other vectors but that's not very important. In these
cases I do something like this:

vector<int> * f() {
vector<int> * v = new vector<int>;
return v;
}

Would there be any other way without pointers?

Would this work:
vector<int>& f() {
vector<int> v;
return v;
}

???

Cheers,

Paulo Matos


vector<int> f()
{
return vector<int>;
}

regards,
ben
Jul 23 '05 #5
pmatos wrote:
Sometimes I have a function which creates an object and returns it.
Some are sets, other vectors but that's not very important. In these
cases I do something like this:

vector<int> * f() {
vector<int> * v = new vector<int>;
return v;
}
Thats usually a wrong way, because calling functions (which means the
programmer of the calling function) usually don't care about data not
created by themself.
Would this work:
vector<int>& f() {
vector<int> v;
return v;
}


Returning a ref to a local object is always wrong. Thinking about your
problem, the question arises:

In the calling function, you can either write:

vector<int> v;
or
vector<int> v = f();

I can't imagine a situation where someone would prefer the second solution.
So I assume you're trying to solve another problem. But without knowing
about it, nobody will be able to help you.

Mathias
Jul 23 '05 #6
"benben" <be******@hotma il.com> schrieb:
vector<int> f()
{
return vector<int>;
}


This will create a copy of the entire vector while the temporary
object will soon be forgotten unless the compiler supports a return
value optimization.

T.M.
Jul 23 '05 #7
Torsten Mueller wrote:
"benben" <be******@hotma il.com> schrieb:
vector<int> f()
{
return vector<int>;
}


This will create a copy of the entire vector while the temporary
object will soon be forgotten unless the compiler supports a return
value optimization.


Even _with_ RVO

vector<int> x = f()

will copy the vector twice.

Jul 23 '05 #8
"Panjandrum " <pa********@spa mbob.com> schrieb:
vector<int> f()
{
return vector<int>;
}


This will create a copy of the entire vector while the temporary
object will soon be forgotten unless the compiler supports a
return value optimization.


Even _with_ RVO

vector<int> x = f()

will copy the vector twice.


I had this in another news group some days ago. Look at the following
program:

#include <iostream>
using namespace std;

struct X
{
X() { cout << "X"; }
X( const X& ) { cout << "C"; }
};

X f()
{
return X();
}

X g()
{
X x;
return x;
}

#define TEST( code ) \
cout << #code << "\t: "; code; cout << endl

int main()
{
TEST( X x1( f() ); );
TEST( X x2( g() ); );
TEST( X const& x3 = f(); );
TEST( X const& x4 = g(); );
}

This little program compiles indeed different with several compilers.
I used the one I had on my machine. Look at this:

------------------------------------------------------------------------
MSVC 6

X x1( f() ); : X
X x2( g() ); : XC
X const& x3 = f(); : X
X const& x4 = g(); : XC
------------------------------------------------------------------------
MSVC 7.1

X x1( f() ); : X
X x2( g() ); : XC
X const& x3 = f(); : X
X const& x4 = g(); : XC
------------------------------------------------------------------------
gcc 3.2.3 (mingw)

X x1( f() ); : X
X x2( g() ); : X
X const& x3 = f(); : X
X const& x4 = g(); : X
------------------------------------------------------------------------
aCC (HP ANSI C++ B3910B A.03.27, HPUX)

X x1( f() ); : XC
X x2( g() ); : XCC
X const& x3 = f(); : X
X const& x4 = g(); : XC
------------------------------------------------------------------------

gcc does never (!) copy. Also the Microsoft compilers do avoid the
copy during return. They copy just the local variable. aCC on HPUX
does indeed copy during return. Because of this differences I would
not use this method of returning an object.

T.M.
Jul 23 '05 #9
Geo wrote:
You should consider returning a
std::auto_ptr, or some other smart pointer.


I agree with this advice. I recommend using a reference counting pointer
such as boost::shared_p tr for this. This will take care of memory
management automatically.

Regards
-Laurens
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
1951
by: Tom Leylan | last post by:
(I posted this in languages.vb also... I can't figure out where things go if you use a little of a lot of things) Hi all... I'm looking for an example (or a pointer to one) related to the following. I have a WebService (it works) that fetches data, turns it into XML and returns it to a vb.net client. The "data" though represents property values for an object which the vb.net client has created and now has to load. Just about every...
0
4248
by: Anonieko Ramos | last post by:
ASP.NET Forms Authentication Best Practices Dr. Dobb's Journal February 2004 Protecting user information is critical By Douglas Reilly Douglas is the author of Designing Microsoft ASP.NET Applications and owner of Access Microsystems. Doug can be reached at doug@accessmicrosystems.com. --------------------------------------------------------------------------------
13
2161
by: andrea | last post by:
Sorry for the stupid question, I know, but sometimes is necessary starts from the basic. I don't know how to pass the result of a method generated from a DAL class to a BL class returning the results as it is. I mean, for instance, something like this. namespace DAL {
13
2331
by: frk.won | last post by:
I am interested in learning how to use the VS 2005 code snippets. However, I wish to know what are the best ways to source control the code snippets? Are there any source safe/subversion add-ons for this purpose? If not, any urls which demonstrates code snippets management?
4
2485
by: barcaroller | last post by:
I am trying to adopt a model for calling functions and checking their return values. I'm following Scott Meyer's recommendation of not over-using exceptions because of their potential overhead. Here's the approach I'm currently looking at. I throw exceptions only from constructors. Destructors, of course, do not throw exceptions. All other functions return a signed integer. The values are all stored in one large header file (as...
8
2437
by: Palindrom | last post by:
Hi everyone ! I'd like to apologize in advance for my bad english, it's not my mother tongue... My girlfriend (who is a newbie in Python, but knows Perl quite well) asked me this morning why the following code snippets didn't give the same result : ### Python ###
0
1618
by: fig000 | last post by:
Hi, I'm using an objectdatasource. The insert procedure called by the objectdatasource is in a separate library file outside of the aspx and the codebehind that is using the objectdatasource in question (I guess that separate file would be called a bll). I had originally used the parameter list method to pass the inserted values to thie insert procedure which also gave me the ability to add a retun parameter to access the newly...
0
9618
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10259
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9906
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7456
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.