copy constructor in g++

S

Sean

the language spec tells us that a temporary class will be created when a
function's return value is an object. And the copy constructor will be
called (if it has been defined) when the temporary object is created.
But when I compile the following code with g++, there is no copy
constructor call. Why?

#include <iostream>
using namespace std;
class myclass{
int i;
public:
myclass(){ cout << "constructor ...\n";}
myclass(const myclass &ob){ cout << "copy constructor...\n";}
~myclass(){ cout << "destructor...\n";}
};
myclass foo(){ myclass temp; cout << "calling foo...\n"; return temp}
int main(){
myclass a;
a = foo();
}

Here I copy the output of the program. Supposely, there should be a
temporary object created, but I don't see its constructing/destructing
procedure, as the output shows. Why does this happen? is it a g++
implementation specific behavior? Thanks

[dash]$g++ copyconstructor1.cpp
[dash]$ a.out
constructor ...
constructor ...
calling foo...
destructor...
destructor...
 
J

John Harrison

Sean said:
the language spec tells us that a temporary class will be created when a
function's return value is an object. And the copy constructor will be
called (if it has been defined) when the temporary object is created.
But when I compile the following code with g++, there is no copy
constructor call. Why?

#include <iostream>
using namespace std;
class myclass{
int i;
public:
myclass(){ cout << "constructor ...\n";}
myclass(const myclass &ob){ cout << "copy constructor...\n";}
~myclass(){ cout << "destructor...\n";}
};
myclass foo(){ myclass temp; cout << "calling foo...\n"; return temp}
int main(){
myclass a;
a = foo();
}

C++ also allows the copy constructor call to be eliminated for
efficiency reasons. It allows this even if the copy constructor has some
side effect.
Here I copy the output of the program. Supposely, there should be a
temporary object created, but I don't see its constructing/destructing
procedure, as the output shows. Why does this happen? is it a g++
implementation specific behavior? Thanks

It is, although I imagine many other compilers would do the same. We had
a recent post here which showed that VC++ 7 eliminated the copy
constructor call only in the case where it was user defined. If it was
not defined then an extra call to the destructor proved that the default
copy constructor was getting called. Maybe you could try the same
experiment.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,153
Latest member
NamKaufman
Top