I wrote the following program to check when the copy constructor is called and when the assignment operator is called:
#include class Test { public: Test() : iItem (0) { std::cout << "This is the default ctor" << std::endl; } Test (const Test& t) : iItem (t.iItem) { std::cout << "This is the copy ctor" << std::endl; } ~Test() { std::cout << "This is the dtor" << std::endl; } const Test& operator=(const Test& t) { iItem = t.iItem; std::cout << "This is the assignment operator" << std::endl; return *this; } private: int iItem; }; int main() { { Test t1; Test t2 = t1; } { Test t1; Test t2 (t1); } { Test t1; Test t2; t2 = t1; } }
This results in the following output (just added empy lines to make it more understandable):
doronw@DW01 : ~ $ ./test
This is the default ctor
This is the copy ctor
This is the dtor
This is the dtor
This is the default ctor
This is the copy ctor
This is the dtor
This is the dtor
This is the default ctor
This is the default ctor
This is the assignment operator
This is the dtor
This is the dtor
The second and third set behave as expected, but in the first set the copy constructor is called even though the assignment operator is used.
Is this behavior part of the C ++ standard or just a clever compiler optimization (I am using gcc 4.4.1)
doron source share