473,788 Members | 2,861 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Copy constructor at return

Hi,

Why g++ in Linux does not call copy constructor at return statement?

I have detected this at Sicentific Linux 4.1 (g++ v. 3.4.3) and Red Hat
Linux 8.0 (g++ v. 3.2).

Microsoft Visual Studio C++ v. 8 at Windows XP calls them as necessary
(as should be according to Stroustrup and my previous experiense),
that is it calls the copy constructor for the object, returned by
"return".

To the contrary, in Linux the copy constructor is NOT called.
How this may happen? The local automatic object should be desrtoyed. How
its content is transferred to outside scope without either constructors,
or assignment operators (they are also not colled, as the code below
shows)?

To illustrate this consider the following simple program and its output
at both Linuxes and at Windows (which is different), see below.

Who knows the explanation of this behaviour of g++, please help me to
understand this!

Thanks
Igor

------------------------------------------------------

#include <iostream>
using std::cout;
using std::ostream;
class X
{
public:
int i; // just anything
X(int fi) {i = fi;}
X( X& fx)
{
cout<<"X::X(X& fx) is called\n";
*this = fx;
}
X(const X& fx)
{
cout<<"X::X(con st X& fx) is called\n";
*this = fx;
}
X& operator=(const X& fx)
{
cout<<"X::opera tor=(const X& fx) is called\n";
if(this != &fx) i = fx.i; return *this;
}
void print(ostream& file)
{
file<<"X::print (): i = "<<i<<'\n';
}
};

X func(int fi)
{
// create local instance of X
X x(fi);
cout<<"func:\n" ;
x.print(cout);
cout<<"calling return\n";
return x;
}

int main(void)
{
X ex1(0);
cout<<"Calling func\n";
ex1 = func(1);
cout<<"func is finished\n";
ex1.print(cout) ;
cout<<"Calling func second time\n";
X ex2( func(2) );
cout<<"func is finished\n";
ex2.print(cout) ;
cout<<"Calling func third time\n";
X ex3 = func(3);
cout<<"func is finished\n";
ex3.print(cout) ;
}

----------------------------------------

Output at Linux & and Windows Parts which appear only at Windows:
(with empty lines added)

Calling func
func:
X::print(): i = 1
calling return
X::X(X& fx) is called
X::operator=(co nst X& fx) is called
X::operator=(co nst X& fx) is called
func is finished
X::print(): i = 1
Calling func second time
func:
X::print(): i = 2
calling return
X::X(X& fx) is called
X::operator=(co nst X& fx) is called
func is finished
X::print(): i = 2
Calling func third time
func:
X::print(): i = 3
calling return
X::X(X& fx) is called
X::operator=(co nst X& fx) is called
func is finished
X::print(): i = 3
--
Sep 22 '06 #1
3 2338
<Ig**********@c ern.chschrieb im Newsbeitrag
news:Pi******** *************** *******@lxplus0 73.cern.ch...
Hi,

Why g++ in Linux does not call copy constructor at return statement?

I have detected this at Sicentific Linux 4.1 (g++ v. 3.4.3) and Red Hat
Linux 8.0 (g++ v. 3.2).

Microsoft Visual Studio C++ v. 8 at Windows XP calls them as necessary
(as should be according to Stroustrup and my previous experiense),
that is it calls the copy constructor for the object, returned by
"return".
....
X func(int fi)
{
// create local instance of X
X x(fi);
cout<<"func:\n" ;
x.print(cout);
cout<<"calling return\n";
return x;
}
The compiler is allowed to optimize the code to eliminate such temporary
objects if the local variable exists as long as a temporary object created
for the return statement would exist. Search for "return value optimization"
for more details. If you'd add messages to your destructor, you would
probably see that the local variable is only destroyed after the assignment
operator in the calling code has been called.

HTH
Heinz
Sep 22 '06 #2
Heinz Ozwirk wrote:
The compiler is allowed to optimize the code to eliminate such temporary
objects if the local variable exists as long as a temporary object created
for the return statement would exist.
Only if there are no side effects. Calls to library functions are side
effects.

Regards,
Bart.

Sep 22 '06 #3
Bart wrote:
Heinz Ozwirk wrote:
>The compiler is allowed to optimize the code to eliminate such temporary
objects if the local variable exists as long as a temporary object
created for the return statement would exist.

Only if there are no side effects. Calls to library functions are side
effects.
Sometimes, and in particular in return value optimization, the compiler is
allowed to eliminate side effects. 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. 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
Best

Kai-Uwe Bux
Sep 22 '06 #4

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

Similar topics

42
5808
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC heap but that doesn't mean that they couldn't be copied from another object of the same kind when...
5
459
by: I wish | last post by:
I wrote some program #include <iostream> class A { public: A() {} A( const A& t ) { std::cout << "Good" << std::endl; } }; A f()
1
2226
by: masood.iqbal | last post by:
I have a few questions regarding overloaded typecast operators and copy constructors that I would like an answer for. Thanks in advance. Masood (1) In some examples that I have seen pertaining to casting class A to class B, the implementation of the
7
2552
by: Kelly Mandrake | last post by:
I've implemented a class with operator+ overloaded and I also provided my own copy constructor; The problem is my copy constructor is being called twise and I dont understand why. I believe the copy constructor is being called when I add the two class objects. But if this is so, then why because I have overloaded the + operator should I not get the result from that and not from copy constructor? I have the following: int main(int...
3
2429
by: bipod.rafique | last post by:
Hello all, Even though this topic has been discussed many times, I still need your help in clearing my confusions. Consider the following code: class aclass{ public: aclass(){
7
1604
by: vj | last post by:
Hi! I recently came across this intresting behaviour shown by Visual C++ 6.0 compiler regarding Copy Constructors. Please tell me that is this the standard behaviour shown by all compilers or its limited only to VC++. Listing 1 ================== #include <iostream> using namespace std;
11
1821
by: csudha | last post by:
Hi all, Can you please explain me the usage of copy constructor and how do we use it. Give me some example. Regards, Sudha.
10
2579
by: utab | last post by:
Dear all, So passing and returning a class object is the time when to include the definition of the copy constructor into the class definition. But if we don't call by value or return by value, we do not need to use the copy-constructor. So depending on the above reasoning I can avoid call by value and return by value for class objects, this bypasses the problem or it seems to me like that. Could any one give me some simple examples...
1
2124
by: blangela | last post by:
3.0 Advanced Topic Addendum There are a few cases where the C++ compiler cannot provide an overloaded assignment operator for your class. If your class contains a const member or/and a reference member, the compiler will not be able to synthesize an assignment operator for your class. It actually helps to think of a reference member as a const member (since it cannot be made to reference any other object once it has been initialized). ...
22
3625
by: clicwar | last post by:
A simple program with operator overloading and copy constructor: #include <iostream> #include <string> using namespace std; class Vector { private: float x,y; public: Vector(float u, float v);
0
10364
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
10110
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
8993
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
7517
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
6750
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
5398
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
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.