Why the copy constructor does not receive the call in this case

Let's say I have class A

Now when i do

A a(A()); 

what exactly is going on?

+4
source share
2 answers

Despite the appearance, A a(A()); not an object definition. Instead, it declares a function called a that returns a and takes a pointer to a function that takes nothing and returns a .

If you need an object definition, you need to add another pair of brackets:

 A a((A())); 
+11
source

If correctly spelled - A a((A())) - the compiler creates temporary content directly in the context of the constructor to prevent an extra copy. It was called copy elision . Take a look at this with RVO and NRVO.

From your comment:

 A a = A(); 

it is exactly equivalent

 A a((A())); // note extra pair of parenthesis 

As @Naveen correctly pointed out, A a(A()); undergoes the most unpleasant analysis, so you need an additional set of paratets for the actual creation of the object.

+8
source

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


All Articles