473,785 Members | 2,619 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
32 2215
"Markus Schoder" <a3************ *@yahoo.de> wrote in message
news:11******** **************@ i40g2000cwc.goo glegroups.com.. .
:Tomás wrote:
:> Roland Pibinger posted:
:>
:> >> When certain criteria are met, an implementation is allowed to omit
:> >> the copy construction of a class object, even if the copy
constructor
:> >> and/or destructor for the object have side effects.
:> >
:> > It's astonishing that Stroustrup let that slip into the language.
:>
:>
:> I disagree entirely -- I think it paves the way for more efficient
:> programming.
:
:I also think RVO is a win.
:
:> If a class has "side effects" because of a copy constructor or
destructor,
:> then it's a stupid class.
:
:Maybe true for the copy constructor for the destructor however side
:effects are not uncommon the whole RAII concept cannot work without
:them (think std::fstream or classes for mutex locking). Of course these
:are not objects you would normally return from a function.

One may want "RAII"-style objects to be returned from functions,
if ownership-transfer semantics are implemented.
Think of std::auto_ptr
Of course, the latter is a bit of a hack in the current C++ standard,
but better support for the concept may soon be integrated in the
core language (look for proposals related to r-value references, the
latest version of which can be found here:
http://www.open-std.org/jtc1/sc22/wg...006/n1952.html ).

Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form

Apr 14 '06 #31

Axel Bock skrev:
Hi Tomas,
[snip] @Squeamizh: Confused is what I was. Still, as I understood, what we
face here is a so-called "return-value-optimization". In that case the
compiler recognizes that this object you return gets assigned to a ...
variable in the calling (!) code, so it will perform all the actions,
but the resulting object will be global. Or in other words: Doing a

SomeObj obj = foo();

translates to something like:

SomeObj &obj;
if (this_or_that) {
// .... yadda ....
obj = /* something smart */
}
else if (blah ...)
{
//.....
obj = /* whatever */
}
/* basically all your foo-code */

(very, very roughly) explained. And all this because the compiler
actually realizes that the _local_ object gets returned and is to be
used in a wider scope.

What happens in practice whenever an object is returned from a function
is that the caller supplies memory for the returned object. Thus

SomeObj func()
{
SomeObj res;
...
returm res;
}

gets translated to

void func(void* area_suitable_f or_SomeObj).
{
SomeObj res;
...
new (area_suitable_ for_SomeObj) SomeObj(res);
}

Now, return value-optimisation allows the function above to be
implemented as:
void func(void* area_suitable_f or_SomeObj).
{
new (area_suitable_ for_SomeObj) SomeObj();
...
}

Notice that all functions that return an object will normally follow
the path above - irrespective of language. Pascal would do it the same
way. It is only when the object returned is small enough to fit into a
(few) register, that this way of passing is not used.

/Peter

Apr 14 '06 #32
I see. Thanks a lot for that clarification! I now understand why is
happening what is happening ;)

cheers,
Axel.

Apr 14 '06 #33

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
6733
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
1882
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
9481
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,...
1
10095
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
9953
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
8978
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
7502
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
5383
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
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4054
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
3
2881
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.