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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With