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.
精彩评论