Big five rule: If you need customized copy ctor, assignment, and
destructor, Then you also need move ctor and move assignment.
Because it include memory allocation inside your class, you need you
own copy ctor to perform deep copy and use move ctor to "move
resource".
Normally, ctor , destructor and assignment should be public. Ininheritance context, all the base class desctructor should bevirtual.
Avoid calling virtual functions in ctor and dtor. "C++ Coding Standards"
item 49.
What does a typical user defined move constructor do?
Assuming the only non-static data in the class is a std::string, here’s the
conventional way (i.e., using std::move) to implement the move constructor:
If you define a specify ctor, you also need to define default ctor.
Because system will not produce any default ctor for you. So below
statement will produce error when compiling.
From previous example, you can see that default ctor is very important. but
when class MUST need another information when create, such as worker
class, You must provide SSN when you create a worker. At this time, if you
create default ctor, It’s not good idea. A NULL SSN will cause a lot
of trouble in the future. So you have to use Worker pointer, and
vector<Worker>. You also need to use delete to disable default ctor. That is
C++ spirit, You never have the best answer, only have contextanswer.
Normally you will have to explicitly declare your own destructor
if:
You are declaring a class which is supposed to serve as a base
for inheritance involving polymorphism, if you do you’ll need a
virtual destructor to make sure that the destructor of a Derived
class is called upon destroying it through a pointer/reference to
Base.
You need to release resourced aquired by the class during its
leftime Example 1: The class has a handle to a file, this needs
to be closed when the object destructs; the destructor is the
perfect location. Exempel 2: The class owns an object with
dynamic-storage duration, since the lifetime of the object can
potentially live on long after the class instance has been destroyed
you’ll need to explicitly destroy it in the destructor.
A copy constructor is called whenever a new variable is created from an
object. This happens:
When a new object is initialized to an object of the same class.
In previous example, you can see when you pass value of obj, It will call
copy ctor, It’s not very efficient. So you should use reference or pointer if it’s
possible, don’t pass object directly.
An Assignment operator examples: 1) avoid assignment self 2) return*this reference.
For reference, once assigned, a reference cannot be re-assigned. So if a class
has a reference member, It can be initialized by initializer list in ctor and
copy ctor. But you can’t overload assignment operator any more, Ifyou really need assignment operator, change reference topointer