Copy non-calling constructor

When I read about copy initialization and direct initialization here . the constructor of the copy should cause the copy to be initialized. why does the constructor not call copy here?

#include <iostream> using namespace std; class A{}; class B{ public: B(const A &a){cout << "B construct from A" << endl;} B(const B &b){cout << "B copy constructor" << endl;} }; int main(){ A a; B b = a; return 0; } 
+4
source share
2 answers

This Copy Elision Link 1:.
Copying constructor calls when generating time series can be optimized by the compiler by creating inline objects, and this is explicitly permitted by the C ++ standard.

This is well demonstrated in the standard as well with an example:

C ++ 03 Standard 12.2 Temporary objects [class.temporary]
Paragraph 2:

 [Example: class X { // ... public: // ... X(int); X(const X&); ˜X(); }; X f(X); void g() { X a(1); X b = f(X(2)); a = f(a); } 

Here, the implementation can use the temporary construct X(2) before passing it to f() using the Xs copy-constructor; alternatively, X(2) may be constructed in the space used to hold the argument. In addition, the temporary can be used to store the result of f(X(2)) before copying it to `b using X 's copyconstructor; alternatively, 's copyconstructor; alternatively, f () 's result might be constructed in b. On the other hand, the expression 's result might be constructed in b. On the other hand, the expression a = f (a) requires a temporary for either the argument a or the result of f (a) to avoid undesired aliasing of a`,]

Link 1:
C ++ 03 12.8 Copying class objects [class.copy]
Paragraph 12:

When certain criteria are met, implementations are allowed to omit the copy construct of the class object , even if the copy constructor and / or destructor for the object have side effects .....

+5
source

The initialization of copying is still dependent on copying, and I assume this is happening. Theoretically, temporary B built from a , and the copy constructor is used to create B from temporary. In practice, the copy can be optimized.

To verify this, you can make the copy constructor private:

 class B{ public: B(const A &a){cout << "B construct from A" << endl;} private: B(const B &b){cout << "B copy constructor" << endl;} }; 

and get a compilation error. This means that the compiler expects the copy constructor to be available, but does not need to be called.

Copying elision is the only case where the observed behavior can be changed.

+5
source

Source: https://habr.com/ru/post/1437336/


All Articles