Discussion
Team LiB
Previous Section Next Section

Discussion

If you need to define any of these three functions, it means you need it to do more than its default behaviorand the three are asymmetrically interrelated. Here's how:

  • If you write/disable either the copy constructor or the copy assignment operator, you probably need to do the same for the other: If one does "special" work, probably so should the other because the two functions should have similar effects. (See Item 53, which expands on this point in isolation.)

  • If you explicitly write the copying functions, you probably need to write the destructor: If the "special" work in the copy constructor is to allocate or duplicate some resource (e.g., memory, file, socket), you need to deallocate it in the destructor.

  • If you explicitly write the destructor, you probably need to explicitly write or disable copying: If you have to write a nontrivial destructor, it's often because you need to manually release a resource that the object held. If so, it is likely that those resources require careful duplication, and then you need to pay attention to the way objects are copied and assigned, or disable copying completely.

In many cases, holding properly encapsulated resources using RAII "owning" objects can eliminate the need to write these operations yourself. (See Item 13.)

Prefer compiler generated special members; only these can be classified as "trivial," and at least one major STL vendor heavily optimizes for classes having trivial special members. This is likely to become common practice.

    Team LiB
    Previous Section Next Section