简体   繁体   中英

Why copy constructor not getting called in this case

Say, I have a class A

Now when I am doing

A a(A()); 

what exactly happens?

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

If you want an object definition, you have to add another pair of parenthesis:

A a((A()));

If written correctly - A a((A())) - the compiler creates the temporary directly in the constructor context to prevent an extra copy. It's called copy elision . Look this up, along with RVO and NRVO.

From your comment:

A a = A();

this is exactly equivalent to

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

As @Naveen correctly pointed out, A a(A()); is subject to most vexing parse, so you need an extra set of paranthesis there to actually create an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM