In the book Generic Programming and the STL (Chinese edition), it says:
X x = X()will call the copy constructor.
It seems a little weird to me. And I write a test program like this
#include <iostream>
class Test {
public:
Test() {
std::cout << "This is ctor\n";
}
Test(const Test&) {
std::cout << "This is copy-ctor\n";
}
};
int main(int argc, char** argv)
{
Test t = Test();
return 0;
}
The output is “This is ctor”. ok, now I’m confused, which is right?
Nomimally yes, a temporary is default-constructed, and then the copy constructor is invoked to copy it into your object
t.However, in practice the copy can be optimised out — even though it has side effects (the console output):
And (in conjunction with the example given in the same clause):
But the copy constructor does still have to exist, even though it might not be invoked.
Anyway, if you compile with optimisations turned off (or, with GCC, possibly
-fno-elide-constructors), you will see: