Re: Avoid automatic copy constructor generation
Jeff Schwab wrote:
One problem with copy constructors (if you have implemented one
explicitly) is that each time you add a new member variable to your
class, you have to remember to add it to the copy constructor (and
assignment operator). This is extremely easy to forget.
You have a reasonable point, but IMO such a class is already responsible
for too many things. If a member requires special handling during
copying, then it can be wrapped in a class whose copy constructor does
the right thing. That special handling should be the wrapper's only
job.
That's a reasonable design. On one hand it simplifies the outer class,
because you don't have to write a copy constructor for the entire class.
On the other hand it adds a small layer of complexity to that special
member. For example assume you have something like this:
class MyClass
{
std::list<Object> objectList;
std::list<Object>::iterator currentObject;
...
};
Let's assume the specification of this code is that 'currentObject'
always points to either an object inside 'objectList', or to
objectList.end().
This class requires a copy constructor and assignment operator if
instances of this class must be copyable. The copy constructor and
assignment operator need to make 'currentObject' to point to the copied
list (rather than the original).
By your suggested design both 'objectList' and 'currentObject' need to
be wrapped inside an inner class if we want to avoid having to write a
copy constructor and assignment operator on the outer class, so it would
become something like:
class MyClass
{
struct ObjectList
{
std::list<Object> objectList;
std::list<Object>::iterator currentObject;
ObjectList(const ObjectList&); // Implement these appropriately
ObjectList& operator=(const ObjectList&);
};
ObjectList objectList;
...
};
Now accessing the 'objectList' member has to always be done with a
"objectList.objectList" (or whatever we want to call the struct
instantiation). Well, I suppose that's a small price to pay for not
having to write a copy constructor and assignment operator for the outer
class...