简体   繁体   中英

C++11 move constructor and assignment operator

A relatively simple question on the implicit usage of move semantics,

When we have

A func();

The following code:

A a;

a = func();

will call A's default constructor then A's copy constructor to create/return the temporary and then the copy assignment operator to assign it to object a.

In case a move constructor and a move assignment have been defined for A, what will be actually called in the last statement for the temporary/rvalue to be created? Will it be the copy constructor followed by move assignment?

Creating the temporary is done with the move-constructor, if there is one and the return value can be treated as an rvalue , otherwise the copy-constructor. This might be elided, if the function is suitable for return-value optimisation.

Assigning to a is done with the move-assignment operator if there is one, otherwise, the copy-assignment operator. This is because the temporary is an rvalue .

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