473,770 Members | 6,105 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++ compiler "return" behavior (guru question ;)

Hi all,

I am trying to get my head around what happens if I return a class
object from a function.
It seems C++ (MinGW) does not invoke the copy constructor if I do
something like this:

SomeObj foo()
{
SomeObj X;
// ....
return X;
}

BUT it does create a new object every time the function is invoked, and
it does seem like these objects are usable (I created a little test
program checking this :).
So basically I can go in main:

int main()
{
// ....
SomeObj bar = foo();
SomeObj bar2 = foo();
// for some strange reason the next thing will fail, though:
SomeObj &bar3 = foo();
}

and I will get two different objects back, both valid. (As commented,
the third will fail with some obscure warning about temporary objects -
but there's no copying taking place, so there's no temp object, AFAIK).
Hm.

So I checked something else:

void foobar()
{
SomeObj IamUseless;
}

That object is actually constructed, but destroyed after the function.
Now I am a bit unsure how the C++ compiler can determine EACH TIME
which object gets returned (maybe in the depth of an STL container of
whatever), and which one does NOT, so this has to be destroyed.

Usually I use new() for factories, but I wondered, and I checked. And I
don't get it :) . So maybe there's a guru in here who can help me out
with some background information? ;)
Cheers & thanks,
Axel.

Apr 9 '06 #1
32 2211
Axel Bock wrote:
Hi all,

I am trying to get my head around what happens if I return a class
object from a function.
It seems C++ (MinGW) does not invoke the copy constructor if I do
something like this:

SomeObj foo()
{
SomeObj X;
// ....
return X;
}
The compiler is free to optimise away the redundant copy in this case.
BUT it does create a new object every time the function is invoked, and
it does seem like these objects are usable (I created a little test
program checking this :).
So basically I can go in main:

int main()
{
// ....
SomeObj bar = foo();
SomeObj bar2 = foo();
// for some strange reason the next thing will fail, though:
SomeObj &bar3 = foo();


You can't bind a temporary object (the function return) to a non-const
reference. Try

const SomeObj &bar3 = foo();

--
Ian Collins.
Apr 9 '06 #2
Hi Ian,

you're right, this works. But why should that return value be a const?
I have declared const nowhere in the whole thing, and there's no
copying between the return value and the used object in main. So I
would say the function's return value is in fact not a temporary
object, and it being const is ... weird. I can modify bar and bar2 all
right ... :)

Basically I wonder about the object created in foo(), because should be
on the stack, in my opinion, and should be destroyed after the
function's scope ends.

But thanks, that answers one question, although replacing it with
another ;)

cheers,
Axel.

Apr 9 '06 #3
Alex,
I hope this answers your question. When an object goes out of scope, it
is destroyed. This doesn't necessarily mean that the memory is erased,
but if you decide to use the object, the behavior is undefined. So
while the object may still be on the stack, there are no guarantees
that it won't be overwriten.

-matt

Apr 9 '06 #4
Axel Bock wrote:
Hi Ian,
Basically I wonder about the object created in foo(), because should be
on the stack, in my opinion, and should be destroyed after the
function's scope ends.

But thanks, that answers one question, although replacing it with
another ;)

cheers,
Axel.

Look for return value optimization.

SomeObj foo()
{
SomeObj X;
return X;
}
int main()
{
// ....
SomeObj bar = foo();
SomeObj bar2 = foo();
// for some strange reason the next thing will fail, though:
SomeObj &bar3 = foo();
}

The memory for bar and bar2 is allocated in main, and foo executes the
constructor for this object.
hth
Klaus

Apr 9 '06 #5
klaus hoffmann wrote:
Look for return value optimization.

SomeObj foo()
{
SomeObj X;
return X;
}


Is return value optimization allowed in this case? I thought it was
only possible for something like

SomeObj foo()
{
return SomeObj();
}

that is an unnamed object. Not sure though.

Apr 9 '06 #6
Markus Schoder posted:
klaus hoffmann wrote:
Look for return value optimization.

SomeObj foo()
{
SomeObj X;
return X;
}


Is return value optimization allowed in this case? I thought it was
only possible for something like

SomeObj foo()
{
return SomeObj();
}

that is an unnamed object. Not sure though.

Yes, it's allowed in both cases above. If the expression after "return" can
used as an l-value, then you're likely to see optimization. For instance:

SomeClassType foo()
{
SomeObj x;

return ++x; //Likely to see optimization
}

SomeClassType foo()
{
SomeObj x;

return x++; //Less likely to see optimization
}
-Tomás
Apr 9 '06 #7
Tomás wrote:
Markus Schoder posted:
klaus hoffmann wrote:
Look for return value optimization.

SomeObj foo()
{
SomeObj X;
return X;
}


Is return value optimization allowed in this case?


Yes, it's allowed in both cases above. If the expression after "return" can
used as an l-value, then you're likely to see optimization. For instance:

SomeClassType foo()
{
SomeObj x;

return ++x; //Likely to see optimization
}

SomeClassType foo()
{
SomeObj x;

return x++; //Less likely to see optimization
}


Checked this now in the Standard. According to 12.8 (15) your examples
both cannot be optimized but the original one (with just return x;) can
indeed. The expression in the return statement has to be the name of a
local object.

Apr 9 '06 #8
Hi all,

thanks for all the answers.
What I would like to clarify now is the "style" of that code: Is that
good style, or not?

I would rather say it's not, cause it surely LOOKS like a local object,
so using that is confusing. Maybe even compiler-dependent, for it is an
"optimizati on"? Anyways I do appreciate the ease of the assignment: To
have a function in which some init / creation / factory stuff can be
done, and assigning the return value without using copy constructors or
pointers. That on the other hand is good. Hm.

:-)

Anyways, cheers and thanks,
Axel.

Apr 10 '06 #9

Axel Bock wrote:
Hi all,

thanks for all the answers.
What I would like to clarify now is the "style" of that code: Is that
good style, or not?
It is good style.

I would rather say it's not, cause it surely LOOKS like a local object,
so using that is confusing.
But it IS a local object. I see nothing confusing about that. What
would be truly confusing would be if assignment created a different
object than copy construction.
Maybe even compiler-dependent, for it is an
"optimizati on"?
You might call it an optimization, but one employed by all compilers i
know. Still the optimization should not change anything for the reasons
stated above.
Anyways I do appreciate the ease of the assignment: To
have a function in which some init / creation / factory stuff can be
done, and assigning the return value without using copy constructors or
pointers. That on the other hand is good. Hm.


/Peter

Apr 10 '06 #10

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

Similar topics

9
1635
by: Ximo | last post by:
Hello, I want that the return sentence don't return anything, how can I do it?. If i do only return it returns None, and pass don't run too. Can anyone help me?, thanks. XIMO
32
8877
by: Mike Machuidel | last post by:
Hi, I'm a game developer programming mostly in C and ASM for about 7 years. Today at work a colleague (a C++ programmer) yelled at me I'm a bad C programmer because I use "return(0);" instead of "return 0;". He explained that "return" is not a function but a stament, like I didn't know already. The other colleagues also argreed with him :(. Can someone please explain what's so wrong about using "return" with
10
2620
by: LaEisem | last post by:
On-the-job, I have "inherited" a lot of old C language software. A question or two about when "casting" of null pointer constants is needed has occurred during behind-the-scenes cleanup of some of that software. That subject seems not to be addressed, at least not directly, in the C FAQ where FAQ 5.2 seems most relevant. References: * C FAQ 5.2 Null pointers (Including conditions where "casting" of null pointer...
15
6731
by: Greenhorn | last post by:
Hi, when a function doesn't specify a return type ,value what value is returned. In the below programme, the function sample()is returning the value passed to 'k'. sample(int); main() { int i = 0,j; j = sample(0);
1
1881
by: Holger (David) Wagner | last post by:
Hi there, we have an application which is built with several ASCX controls some of which contain form elements (e.g. Textboxes, Buttons etc.) For example: in the top section (one ascx-control), there is a textbutton in which the user can enter a string to search for. There's link button right next to that textbutton. Then, in the "content section" (another ascx-control), there may be a login-dialog which prompts the user for...
0
9592
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
10231
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...
0
10059
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10005
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
9871
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
8887
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...
0
6679
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();...
1
3972
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
3576
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.