473,396 Members | 1,989 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Safe to return a local object?

Tom


I come from C but don't really understand why in C++ you can return a temporary object
from a function.
For example:

class Test {
public:

Test() { cout << "Address of object: " <<this <<endl; }
~Test() { }
};

Test func() {
Test tmp;
cout << "func(): Address of tmp: " << &tmp <<endl;
return tmp;
}

int main() {

Test a = func();
cout <<"main(): Address of a: " <<&a <<endl;
}
Output:
func(): Address of tmp: 0x22ff30
main(): Address of a: 0x22ff30
The output shows the same address on the stack for the two objects, but the same code in C
using structures instead of classes shows a different address ("tmp" local to the func stack
and "a" local to main).

So I have some questions:

Aren't local variables (and objects) created in the stack?
If so, why the local object is not destroyed after the function call?
Shouldn't they point to different addresses, with a local copy for each one?
Thanks for any clearing of confusion you can contribute...
May 16 '06 #1
4 4908
Tom wrote:
Test a = func();
cout <<"main(): Address of a: " <<&a <<endl; Output:
func(): Address of tmp: 0x22ff30
main(): Address of a: 0x22ff30


The compiler had the option to create two objects, and call a copy
constructor.

However, you wrote a detector for the "return value optimization". Google
for that. It essentially means the compiler is free to secretly pass a
_into_ func(), to construct it in that context, and to skip the copy
construction at return time.

The Standard defines this optimization because without it, the compiler
would not know how to optimize this situation, because a programmer might
depend on a side-effect of the copy constructor. Without the RVO rule, if
the compiler aggressively optimized this code, the side-effect would
disappear and the code would break.

With this rule, developers are instructed not to rely on side-effects, such
as the one you discovered. And the compiler can optimize better. Without
this rule, we would be forced to write ugly code that avoided the extra
constructor and copy operation. So the rule permits cleaner code.

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
May 16 '06 #2
Tom wrote:
I come from C but don't really understand why in C++ you can return a
temporary object
from a function.
There is this magical place where temporary objects are born and live their
wonderous lives. C doesn't have it.
For example:

class Test {
public:

Test() { cout << "Address of object: " <<this <<endl; }
~Test() { }
};

Test func() {
Test tmp;
cout << "func(): Address of tmp: " << &tmp <<endl;
return tmp;
}

int main() {

Test a = func();
cout <<"main(): Address of a: " <<&a <<endl;
}
Output:
func(): Address of tmp: 0x22ff30
main(): Address of a: 0x22ff30
There seems some output missing...
The output shows the same address on the stack for the two objects,
but the same code in C using structures instead of classes shows a
different address ("tmp" local to the func stack and "a" local to
main).

So I have some questions:

Aren't local variables (and objects) created in the stack?
That's what some believe. The Standard doesn't say where local objects
are created.
If so, why the local object is not destroyed after the function call?
The compiler could be optimizing all the copying away.
Shouldn't they point to different addresses, with a local copy for
each one?


They don't have to. The compiler can optimize creation of any objects
it pleases. Even if the constructors have side effects.

V
--
Please remove capital As from my address when replying by mail
May 16 '06 #3
Local variables are destroyed at the time of return but in c++ copy
contructor creates a copy of that object, just write ur own copy
contructor in this program like
Test(Test& a)
{
cout<<"Copy constructor ::";
cout<<this<<endl;
}
and you will see two different objects got created, write one cout in
ur destructor and you will see that before the function was returned
the copy contrutor was called to make a new copy of the object and then
temporary object was destroyed.

May 16 '06 #4
ra*************@gmail.com wrote:
Local variables are destroyed at the time of return but in c++ copy
contructor creates a copy of that object, just write ur own copy
contructor in this program like
Test(Test& a)
{
cout<<"Copy constructor ::";
cout<<this<<endl;
}
and you will see two different objects got created, write one cout in
ur destructor and you will see that before the function was returned
the copy contrutor was called to make a new copy of the object and then
temporary object was destroyed.


That's another example of a side-effect that might disappear with RVO.

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
May 16 '06 #5

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

Similar topics

12
by: Olumide | last post by:
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is an absolutely fantastic book; however on page 175 (topic: operator overlaoding), there the following code snippet: inline...
1
by: Pradeep Kumar | last post by:
I have a scenario where I am writing a property(using get and set) have to return a member of an object stored in an array of objects! The class user has to pass an index based on which a object i's ...
0
by: ddt | last post by:
Hi, I have an application which need return a sort of similar objects from one function, can I defined web method return as object and to return different objects from it? Thanks in advance.
4
by: Macca | last post by:
Hi, I've been reading the online documentation for the System.Collections.Queue object on how to implement a threadsafe Queue object. I understand the basics, by using the wrapper returned by...
3
by: Steven W. Orr | last post by:
When I go to create an object I want to be able to decide whether the object is valid or not in __init__, and if not, I want the constructor to return something other than an object, (like maybe...
12
by: =?Utf-8?B?RXRoYW4gU3RyYXVzcw==?= | last post by:
Hi, I have a class which "BiologySequence" which looks about like this. public class BiologySequence { private string _Sequence; public string Sequence {
3
by: George2 | last post by:
Hello everyone, 1. Returning non-const reference to function local object is not correct. But is it correct to return const reference to function local object? 2. If in (1), it is correct...
0
by: Ryan Liu | last post by:
Why IDataParameterCollection.Item return an object, not a IDataParameter? Like DbParameterCollection .GetParameter() -DbParameter Thanks! Ryan
13
by: WaterWalk | last post by:
Hello. When I consult the ISO C++ standard, I notice that in paragraph 3.6.2.1, the standard states: "Objects with static storage duration shall be zero-initialized before any other...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...

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.