Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guidance for when to explicitly enable/disable copying in C++ classes?

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!

like image 951
John Avatar asked Dec 05 '22 21:12

John


1 Answers

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.

like image 140
James Kanze Avatar answered Jan 03 '23 08:01

James Kanze