I was doing some tests on copy constructors and operator=, but I got some weird results.
Here are my two test files test.h and test.cpp:
test.h
class CopyC {
public:
CopyC() {
cout << ">> In Default Constructor" << endl;
}
CopyC(const CopyC &other) {
cout << ">> In Copy Constructor" << endl;
}
~CopyC() {
cout << ">> In Deconstructor" << endl;
}
CopyC& operator=(const CopyC &other) {
cout << ">> In Operator =" << endl;
return *this;
}
CopyC getCopy() {
cout << ">> In getCopy" << endl;
cout << "return CopyC()" << endl;
return CopyC();
}
};
test.cpp
#include "test.h"
int main() {
cout << "CopyC c1" << endl;
CopyC c1;
cout << "CopyC c2 = c1.getCopy()" << endl;
CopyC c2 = c1.getCopy();
cout << "<< Finish" << endl;
}
I was using gcc 4.6.3 on linux amd64 with the command g++ -o test -g3 test.cpp
. The output of ./test
is
CopyC c1
>> In Default Constructor
CopyC c2 = c1.getCopy()
>> In getCopy
return CopyC()
>> In Default Constructor
<< Finish
>> In Deconstructor
>> In Deconstructor
It seems that neither the copy constructor nor the operator= are invoked in the getCopy function. Did I missed something or I misunderstood something? Please help. Thanks in advance.
update:
Thanks to @Mike Seymour, now I know that this is a problem of copy elision. When I disabled g++ copy elision with g++ -o test test.cpp -fno-elide-constructors
, the output looks more resonable:
CopyC c1
>> In Default Constructor
CopyC c2 = c1.getCopy()
>> In getCopy
return CopyC()
>> In Default Constructor
>> In Copy Constructor
>> In Deconstructor
>> In Copy Constructor
>> In Deconstructor
<< Finish
>> In Deconstructor
>> In Deconstructor