Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we be calling the base class move copy/assignment constructors from the derived class

Tags:

c++

c++11

I understand that whenever a custom copy constructor or an assignment operator is defined in a derived class then it is the responsibility of those methods to call the respective methods of the base class. Now my focus is on the move constructors. Suppose the following is my move constructor. I have two ways of calling the base class constructor. Taken from here

Derived(Derived&& d):Base(d) -->Form A
{}
Derived(Derived&& d):Base(std::move(d)) -->Form B
{}

Now which method is correct. From my understanding and from the last answer on the post using Form B would be dangerous and incorrect as the object will be nullified when the derived class constructor is called.However in formA the base class copy constructor is called. Would it be better to call FormA . Similarly in the move copy assignment operator wouldn't it be better to call the base class assignment operator then the base class.

like image 441
MistyD Avatar asked Oct 20 '22 11:10

MistyD


1 Answers

Form A is incorrect. It does not implement the move semantics. With respect to the version Form B, the statement that "d is nullified by Base(std::move(d))" is inaccurate. The accurate statement should be "the Base part (subobject) of d is nullified".

Besides ,I suggest you to explicitly cast d to the base type before invoking the base constructor. That is, Base(std::move(static_cast<Base&>(d))). This avoids potential problems if Base has a template constructor. For example, consider the case when Base is std::function. Without the explicit cast, you will end up with infinite recursion because of constructor (5) of std::function.

like image 50
Lingxi Avatar answered Oct 24 '22 03:10

Lingxi