473,785 Members | 2,792 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
The problem is that you ignore possible side effects in the copy
constructor and the destructor.


If the classes with which you are working were written "properly", then the
sideeffects of a copy-construction/destruction should be irrelevant. All
you should notice is that the execution time goes up on account of invoking
the copy constructor and subsequently, the destructor.
-Tomás

Apr 12 '06 #21
Hi all,

first of all thanks for all that information :) . But what I want to
clarify still is that _there is no copying taking place_.

In my logic, if an object gets copied, the copy constructor is used. I
implemented this one with a textual message, and this one gets never,
ever called. In the example that means that

SomeObj obj = foo();

does create an object in the foo() function, which will be assigned
directly to obj. No copying. Also it is the same object by pointer, I
compared the values. Hm.

Again: NO copying there. That's what irritated me.

:-) .
Cheers,

Axel.

Apr 13 '06 #22
In message <11************ **********@v46g 2000cwv.googleg roups.com>, Axel
Bock <ax************ @googlemail.com > writes
Hi all,

first of all thanks for all that information :) . But what I want to
clarify still is that _there is no copying taking place_.

In my logic, if an object gets copied, the copy constructor is used. I
implemented this one with a textual message, and this one gets never,
ever called. In the example that means that

SomeObj obj = foo();

does create an object in the foo() function, which will be assigned
Not _assigned_. The assignment operator isn't used either.
directly to obj. No copying. Also it is the same object by pointer, I
compared the values. Hm.

Again: NO copying there. That's what irritated me.

:-) .
Cheers,

Axel.


--
Richard Herring
Apr 13 '06 #23
Axel Bock wrote:
Hi all,

first of all thanks for all that information :) . But what I want to
clarify still is that _there is no copying taking place_.

In my logic, if an object gets copied, the copy constructor is used. I
implemented this one with a textual message, and this one gets never,
ever called. In the example that means that

SomeObj obj = foo();

does create an object in the foo() function, which will be assigned
directly to obj. No copying. Also it is the same object by pointer, I
compared the values. Hm.

Again: NO copying there. That's what irritated me.


Here is some relevant language from the standard [12.8./15]:

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. In such cases, the
implementation treats the source and target of the omitted copy operation
as simply two different ways of referring to the same object, and the
destruction of that object occurs at the later of the times when the two
objects would have been destroyed without the optimization.11 1) This
elision of copy operations is permitted in the following circumstances
(which may be combined to eliminate multiple copies):

? in a return statement in a function with a class return type, when the
expression is the name of a non-volatile automatic object with the same
cv-unqualified type as the function return type, the copy operation can
be omitted by constructing the automatic object directly into the
function?s return value

? when a temporary class object that has not been bound to a reference
(12.2) would be copied to a class object with the same cv-unqualified
type, the copy operation can be omitted by constructing the temporary
object directly into the target of the omitted copy

[Example:
class Thing {
public:
Thing();
?Thing();
Thing(const Thing&);
};

Thing f() {
Thing t;
return t;
}

Thing t2 = f();

Here the criteria for elision can be combined to eliminate two calls to
the copy constructor of class Thing: the copying of the local automatic
object t into the temporary object for the return value of function f()
and the copying of that temporary object into object t2. Effectively, the
construction of the local object t can be viewed as directly initializing
the global object t2, and that object?s destruction will occur at program
exit. ?end example]
Best

Kai-Uwe Bux
Apr 13 '06 #24

Roland Pibinger wrote:
On 12 Apr 2006 04:41:13 -0700, "Gavin Deane" <de*********@ho tmail.com>
wrote:
So what can a programmer do differently if they know return value
optimisation will be performed? Nothing. There is no code you can write
that would only be correct if return value optimisation were performed.
There is nothing you can write in main to violate the scoping rules
that apply to X and bar if the optimisation is performed. So there is
no problem with this style.


The problem is that you ignore possible side effects in the copy
constructor and the destructor.


That's a different point. I was addressing the OP's apparent concern
that there is something somehow unsafe about return value optimisation.

Your point is only a problem if you write copy constructors and
destructors with side effects. *If* you do that, *and* it is necessary
that the side effects happen, clearly you must avoid using objects of
that type in any situation where the language allows temporary copies
to be elided. Depending on the particular situation, a rethink of the
design may be a better long-term solution.

Gavin Deane

Apr 13 '06 #25

Axel Bock skrev:
Hi all,

first of all thanks for all that information :) . But what I want to
clarify still is that _there is no copying taking place_.
Right. The standard says so, so it should not be to surprising.
In my logic, if an object gets copied, the copy constructor is used. I
implemented this one with a textual message, and this one gets never,
ever called. In the example that means that

SomeObj obj = foo();

does create an object in the foo() function, which will be assigned
directly to obj. No copying. Also it is the same object by pointer, I
compared the values. Hm.
First of all, the fact that you did notice in the first place is what
should really worry you. This means that you use the assignment
operator for something that is not assignment. While this technically
is legal it is confusing in the same way as if you used operator+ to do
division,
Secondly, I wonder (wearing my technical glasses) how you can be so
sure that it is the same object. That they have the same adress does
not imply they are equal. Memory IS allowed to be reused, you know -
much to the discontent of the RAM-producers.

/Peter
Again: NO copying there. That's what irritated me.

:-) .
Cheers,

Axel.


Apr 13 '06 #26
The following code calls a constructor and a destructor.

void fn1 (void)
{
Object obj;
}

The following code has a constructor call for the local object, followed
by a copy constructor for the return, and then a destructor for the
local object.

Object fn2 (void)
{
Object obj;
return obj;
}

The following code has a constructor call, followed by a copy constructor.

Object fn3 (void)
{
return *new Object; // "bad" style :)
}

In fn2 the compiler is allowed to omit the copy by constructing the
object "in-place" of the return value; in MSVC this is accomplished by
passing in the address to construct the object. This is a desirable
effect.
Apr 13 '06 #27
On Thu, 13 Apr 2006 05:28:02 -0400, Kai-Uwe Bux <jk********@gmx .net>
wrote:
Here is some relevant language from the standard [12.8./15]:

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.
Apr 13 '06 #28
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.

If a class has "side effects" because of a copy constructor or destructor,
then it's a stupid class.

-Tomás
Apr 14 '06 #29
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.

Apr 14 '06 #30

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
9645
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
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,...
0
10336
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
10155
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
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,...
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
6741
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
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
2
3655
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.