简体   繁体   中英

c++ make implicit copy constructor use initialization list

We all know that the implicit copy constructor operates as follows: default construct all member variables, then assign each member variable the appropriate corresponding value.

Often I desire a copy constructor which initializes each member variable as a copy, rather than default constructing and then assigning. (eg I have some const member variables).

Question: Manually writing a copy constructor which initializes each member variable as a copy is very tedious, and verges on ridiculous as the number of member variables grows. Is there any way to make the implicit copy constructor use initialization lists? Is there any other way around manually writing the initialization list?

We all know that the implicit copy constructor operates as follows: default construct all member variables, then assign each member variable the appropriate corresponding value.

No, it does not really work like that. Paragraph 12.8/15 of the C++11 Standard specifies:

The implicitly-defined copy/move constructor for a non-union class X performs a memberwise copy/move of its bases and members . [...] Each base or non-static data member is copied/moved in the manner appropriate to its type:

— if the member is an array, each element is direct-initialized with the corresponding subobject of x ;

— if a member m has rvalue reference type T&& , it is direct-initialized with static_cast<T&&>(xm) ;

otherwise, the base or member is direct-initialized with the corresponding base or member of x .

In other words:

Often I desire a copy constructor which initializes each member variable as a copy, rather than default constructing and then assigning. (eg I have some const member variables).

Your wish is already reality.

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