Guide to enable / disable copying in C ++ classes.

An employee cleans up several libraries. In doing so, he read the API design for C ++, and he talks about explicitly allowing or disabling copying in C ++ classes. This is the same as Sutter and Alexandrescu say in their C ++ coding standards.

He agrees that this advice should be followed, but what no book seems to be saying is the principles that determine when to turn it on or off.

Any guidance anyway? Thanks!

+4
source share
5 answers

It depends on the role the classes play in the application. If class is a value where identification does not matter, you must prohibit copy and assignment. Similarly, if the class is polymorphic. As a rule, as a rule, if you select objects of a class type dynamically, it should not be flexible. And vice versa, if you copy a class, you should not select its instances dynamically. (But there are some exceptions, and it is not uncommon to allocate dynamically and avoid copying large objects, even if the semantics say otherwise.)

If you are developing a low-level library, the choice is less clear. Something like std::vector can play a lot of role in the application; in most of them, copying would be inappropriate, but the prohibition of copying would make it unusable in the few where appropriate.

+6
source

Classes that are not copied should be the exception, not the rule. Your class should be incompatible if and only if you cannot preserve the semantics of the values โ€‹โ€‹when copying, for example, with the name mutexes, unique owner pointers. In addition, your class must be copied. Many C ++ libraries depend on the ability to copy, especially pre-C ++ 0x, where they cannot be movable.

+5
source

Unlike DeadMG, I believe that most classes should not be copied.

Here is what Straustrup wrote in his book Design and Evolution of C ++:

"I personally find it sad that copy operations are defined by default, and I prohibit copying objects from many of my classes."

+5
source

I think you should try to write as little code as possible so that the class does what it should do. If no one is trying to copy the class, and it will not be copied in the near future, then do not add such things as the copy constructor or assignment operator. Just make the class incompatible.

When ever you really want to copy a class, add things like the copy constructor. But as long as the non copyable class means less code for testing and support.

0
source

I sincerely believe that the semantics of the copy should be provided automatically or not at all.

However, poorly written libraries can sometimes be extracted from the manual copy constructor.

Note that in C ++ the situation is very different (because copy semantics are usually required by the standard library!) Than in C ++ 0x, where my advice is always applied.

0
source

All Articles