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?
Factor out the common code to a private member function. A simple (rather contrived) example:
#include <iostream>
class Test
{
public:
Test(const char* n)
{
name = new char[20];
strcpy(name, n);
}
~Test()
{
delete[] name;
}
// Copy constructor
Test(const Test& t)
{
std::cout << "In copy constructor.\n";
MakeDeepCopy(t);
}
// Assignment operator
const Test& operator=(const Test& t)
{
std::cout << "In assignment operator.\n";
MakeDeepCopy(t);
}
const char* get_name() const { return name; }
private:
// Common function where the actual copying happens.
void MakeDeepCopy(const Test& t)
{
strcpy(name, t.name);
}
private:
char* name;
};
int
main()
{
Test t("vijay");
Test t2(t); // Calls copy constructor.
Test t3("");
t3 = t2; // Calls the assignment operator.
std::cout << t.get_name() << ", " << t2.get_name() << ", " << t3.get_name() << '\n';
return 0;
}
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.
My &My::operator = (My temp) // thanks, sellibitze
{
swap (*this, temp);
return *this;
}
and implement a specialised std::swap<> (My &, My &)
.
As has already been pointed out by quite a few posters, having operator= create a new object with the copy constructor and then use swap is the common technique used to not have to replicate code in operator=.
That said, I want to point out some a pro and a con of this technique to help you decide whether it is appropriate.
Pro - exception safety
If your object has resource requirements that could cause a throw and assuming that swap will not throw, this technique provides the strong guarantee of exception safety (either the object being assigned to has taken on the value of the other object or it is unchanged).
Con - resource footprint
An issue with this technique is that it requires a complete new object to be created before the old one is released. If your object requires a lot of resources, this can be a problem.