开发者

in C++, How can I give a class copy constructor and assignment operator the same functionality without making duplicate code [duplicate]

开发者 https://www.devze.com 2023-02-12 05:48 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: What is the copy-and-swap idiom?
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

What is the copy-and-swap idiom?

Copy constructor and = operator overload in C++: is a common function possible?

Is there a way that I can make the body of the copy constructor and assignment operator contai开发者_C百科n the same code without actually having duplicate code (except for the function headers)?


One common way is the copy-and-swap idiom. You would have to implement a swap operation, but if done correctly, you have the additional benefit of having exception safe assignment.


Create a function

    init(various parameters you need){
...
//common initializing process
}

then call this function from all you constructors, copy, and assignments operators


Place the functionality in a separate method and then call that from both your copy constructor and assignment operator code.

Alternatively, you could just call your assignment operator from the copy constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消