A colleague is cleaning up a couple of libraries. In doing so he's been reading API design for C++ and it talks about explicitly enabling or disabling copying in C++ classes. This is the same thing that Sutter and Alexandrescu say in their C++ Coding Standards.
He agrees that one should follow this advice, but what neither book seems to say are what are those guiding principles that tell when to enable or disable.
Any guidance one way or the other? Thanks!
It depends on the role the classes play in the application. Unless the class represents a value, where identity isn't significant, you should ban copy and assignment. Similarly if the class is polymorphic. As a generally rule, if you're allocating objects of the class type dynamically, it shouldn't be copiable. And inversely, if the class is copiable, you shouldn't allocate instances of it dynamically. (But there are some exceptions, and it's not rare to allocate dynamically and avoid copying big objects, even when the semantics argue otherwise.)
If you're designing a low-level library, the choice is less clear.
Something like std::vector
can play many roles in an application; in
most of them, copying wouldn't be appropriate, but banning copy would
make it unusable in the few where it is appropriate.