Constructor or copy constructor?

The book Generic Programming and STL (Chinese edition) says:

X x = X() will call the copy constructor.

It seems a little strange to me. And I'm writing 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; } 

Exit: "This is ctor." ok now i'm confused what is right?

+8
c ++ constructor copy-constructor
source share
3 answers

Nomimally yes, the temporary one is built by default, and then a copy constructor is created to copy it to your t object.

However, in practice, a copy can be optimized - even if it has side effects (console output):

[n3290: 8.5/16] : [..] In some cases, the implementation is allowed to exclude copying inherent in this direct initialization by directly constructing the intermediate result in an initialized object; see 12.2, 12.8.

And (in combination with an example in the same sentence):

[n3290: 12.2/2] : [..] An implementation can use a temporary one that must build X (2) before passing it to f () using the X s copy constructor; alternatively, X(2) may be constructed in the space used to hold the argument. [..]

But the copy constructor must still exist, even if it cannot be called.

In any case, if you compile with optimizations disabled (or, with GCC, possibly -fno-elide-constructors ), you will see:

 This is ctor This is copy-ctor 
+9
source share

In theory, X x = X() will call the default constructor to create a temporary object and copy it to x using the copy constructor.

In practice, compilers are allowed to directly skip the copy construction part and the default construction x (which, as David points out in his comment, still requires the copy constructor to be syntactically accessible). Most compilers do this, at least when optimization is turned on.

+4
source share

This is the case when the Return Value Optimization (RVO) form (also known as Copy Elision ) can help a lot in optimization. The related wikipedia page has a very good explanation of what is happening.

+2
source share

All Articles