473,671 Members | 2,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to return reference to class object from functions?

Suppose I have a function foo() and a class definition myClass, and I
want to create an instance of myClass and return it from foo(). I guess
the most efficient way is to return a reference to the object.

But here comes the problem: the object is a local one and will be
detroyed after function return. How can I return the reference from foo()?

Code:

myClass& foo()
{
myClass myObject;

...

return myObject; //Oops, myObject is a local one
}

Jul 19 '05 #1
3 28122
Wang Tong <wa******@seas. upenn.edu> wrote in message
news:bo******** ***@netnews.upe nn.edu...
Suppose I have a function foo() and a class definition myClass, and I
want to create an instance of myClass and return it from foo(). I guess
the most efficient way is to return a reference to the object.
But here comes the problem: the object is a local one and will be
detroyed after function return. How can I return the reference from foo()?

Code:

myClass& foo()
{
myClass myObject;

...

return myObject; //Oops, myObject is a local one
Right, so you can't do that.
}


If you examine your own words carefully, you should be able to deduce that
this is not an appropriate occasion for returning a reference. The reason
that returning a reference is efficient is that you aren't copying the local
object, but if you don't copy the local object it will no longer exist after
the function returns. In other words, the reason a reference is efficient is
also the reason you can't use one (in this case).

Of course there are other occasions - such as a class member function
returning a reference to a data member - in which the referred-to object is
not destroyed when the function returns. In those cases returning a
reference is okay.

DW

Jul 19 '05 #2

"Wang Tong" <wa******@seas. upenn.edu> wrote in message news:bo******** ***@netnews.upe nn.edu...
Suppose I have a function foo() and a class definition myClass, and I
want to create an instance of myClass and return it from foo(). I guess
the most efficient way is to return a reference to the object.

But here comes the problem: the object is a local one and will be
detroyed after function return. How can I return the reference from foo()?

Code:

myClass& foo()
{
myClass myObject;

...

return myObject; //Oops, myObject is a local one
}


Code:

myClass& foo()
{
static myClass myObject;

...

return myObject; //myObject is static
}

-X
Jul 19 '05 #3

"Wang Tong" <wa******@seas. upenn.edu> wrote in message
news:bo******** ***@netnews.upe nn.edu...
Suppose I have a function foo() and a class definition myClass, and I
want to create an instance of myClass and return it from foo(). I guess
the most efficient way is to return a reference to the object.

But here comes the problem: the object is a local one and will be
detroyed after function return. How can I return the reference from foo()?

Code:

myClass& foo()
{
myClass myObject;

...

return myObject; //Oops, myObject is a local one
}

I believe it is much better to return by value in your case.
Static myObject may fail (it depends upon the internal logic of foo) in
expressions like this:
myClass aClass = foo() + foo();
Consider the case when foo modifies myObject. If you bring yourself to make
it static then it shall be properly documented.

In case of return by value a smart compiler would change the foo call:
myClass aClass(foo());
to something like this:
char __myClass_place holder[sizeof(myClass)];
foo(__myClass_p laceholder);
myClass& aClass = *reinterpret_ca st<myClass*>(__ myClass_placeho lder);
...
~aClass();

If you believe you suffer performance penalties due to foo-like code then
you might wish to consider bridge pattern.

--
Michael Kochetkov.
Jul 19 '05 #4

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

Similar topics

94
13861
by: John Bailo | last post by:
The c# *return* statement has been bothering me the past few months. I don't like the fact that you can have different code paths in a method and have multiple return statements. To me, it would be more orthogonal if a method could only have one return statement. --
19
2791
by: Christian Engström | last post by:
If you have a function that returns something by value, the gcc compiler (version 3.2.3 on Windows XP with MinGW) converts the returned value from the type you specify in the code, to the const version of that type. Is this a bug that is specific to gcc, or is it a flaw in the language specification that gcc diligently implements? For example, the below program produces the output Constant Mutable
3
1597
by: Zork | last post by:
Hi, I am a little confused with const functions, for instance (here i am just overloading the unary+ operator) if i define: 1) Length Length :: operator+ ( void ) const {return * this;} ... I get no error... 2) Length & Length :: operator+ ( void ) const {return * this;} ... I get the error -> 'return' : cannot convert from 'const class Length' to
8
3073
by: DaKoadMunky | last post by:
Please consider the following... <CODE> #include <string> using namespace std; typedef int PrimitiveType; typedef string ClassType;
5
3040
by: Neal Coombes | last post by:
Posted to comp.lang.c++.moderated with little response. Hoping for better from the unmoderated groups: -------- Original Message -------- Subject: Return appropriately by value, (smart) pointer, or reference Date: 27 Aug 2005 15:13:23 -0400 From: Neal Coombes <nealc@trdlnk.com> Organization: Aioe.org NNTP Server To: (Usenet) Newsgroups: comp.lang.c++.moderated
5
1351
by: jmd | last post by:
hello. i am trying VC++ 7.1 (with vsnet 2003). my example : class Complex { public: Complex ( float re_ = 0.0, float im_ = 0.0 ) : re(re_), im(im_) {} float Re () { return ( re ); } float Re ( float re_ ) { return ( re = re_ ); }
13
5156
by: ctor | last post by:
Hi, I'm experiencing an annoying issue. Here is a simplified idea of what I am trying to do. Inclusion guards aren't shown for readability. I hope this isn't too confusing; I don't think a description would be as clear as an example. ----------- class ParentA {};
5
2068
by: Tom | last post by:
If I have a container class that has a map member which stores pointers to objects that have been created via the new operator and I have a method that returns a entry in the map, would it be best to return the entry as a dereferenced pointer so it becomes a class or return a reference to the dereferenced class? I believe that it would be best to dereference the class pointer retrieved from the map and then send it back as a reference to...
46
3833
by: Steven T. Hatton | last post by:
I just read §2.11.3 of D&E, and I have to say, I'm quite puzzled by what it says. http://java.sun.com/docs/books/tutorial/essential/concurrency/syncrgb.html <shrug> -- NOUN:1. Money or property bequeathed to another by will. 2. Something handed down from an ancestor or a predecessor or from the past: a legacy of religious freedom. ETYMOLOGY: MidE legacie, office of a deputy, from OF, from ML legatia, from L legare, to depute, bequeath....
0
8930
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
8605
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
8677
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...
0
7446
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6238
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...
0
5704
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4227
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4417
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2062
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.