Why do you create a copy / move constructor or destructor by default?

C ++ 0x allows you to specify specific functions by default:

struct A { A() = default; // default ctor A(A const&) = default; // copy ctor A(A&&) = default; // move ctor A(Other); // other ctor ~A() = default; // dtor A& operator=(A const&) = default; // copy assignment A& operator=(A&&) = default; // move assignment }; 

The implementation of these functions is the same as if the compiler generated them, which usually happens in most cases when you do not declare your own.

By default, ctor is not generated if you declare any ctor (any of the above), so you may need to return it by default.

However, if a database or data element does not exclude them, the class always has a copy and moves ctor⁠-⁠, and if they are excluded, the default implementation will not work. A class always has a dtor.

Why do you need to explicitly specify a copy of ctor, move ctor or destructor? One way or another, will they not implicitly generated implementations do the same?

+6
c ++ c ++ 11
source share
2 answers

You may need to do this in order to change their access to non-public ones or to control which translation unit defines them.

Non-public

Although these functions are publicly available, you may wish to be non-public, but still wish to implement them by default:

 struct A { protected: ~A(); private: A(); A(A const&); A(A&&); }; // according to N3092, Β§8.4.2/2, cannot be non-public and defaulted // in the class definition A::~A() = default; A::A() = default; A::A(A const&) = default; A::A(A&&) = default; 

This class can be constructed by default, copied and moved by default, but only using methods and friends of A. This is useful for factories where construction can be more tightly controlled.

The protected destructor is the second half of the public-virtual / protected-non-virtual landmark for the base classes:

Guideline 4: The base class destructor must be open or virtual, or secure and non-virtual.

Definition Control

In addition, default functions can be used to maintain a stable binary interface, since you have control over where the default functions are defined. Defaulted does not imply inline, as implied declared versions will be. (In the above code, the default functions should either not be in the header or have a built-in qualifier.)

+10
source share

In addition to functional goals, I find this useful for clarity. This makes it clear that the structure must be constructive by default (or something else) and that we use the behavior generated by the compiler. The more your code itself documents, the better.

+1
source share

All Articles