I have a class that requires a non-default copy constructor and assignment operator (it contains lists of pointers). Is there any general way to reduce the code duplication between the copy constructor and the assignment operator?
Constructor: It is a method which has the same name as the class which is used to create an instance of the class. Copy Constructor: Used to create an object by copying variables from another object of the same class.
Advantages of Copy ConstructorIf a field declared as final, the copy constructor can change it. There is no need for typecasting. Its use is easier if an object has several fields. Addition of field to the class is easy because of it.
There's no "general way" for writing custom copy constructors and assignment operators that works in all cases. But there's an idiom called "copy-&-swap":
class myclass
{
...
public:
myclass(myclass const&);
void swap(myclass & with);
myclass& operator=(myclass copy) {
this->swap(copy);
return *this;
}
...
};
It's useful in many (but not all) situations. Sometimes you can do better. A vector or a string could have a better assignment which reuses allocated storage if it was large enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With