Should we call the base class to move copy / assign constructors from the derived class

I understand that whenever a custom copy constructor or assignment operator is defined in a derived class, these methods must answer calls to the corresponding methods of the base class. Now I'm focused on move constructors. Suppose this is my move constructor. I have two ways to call 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 the last response to a message using form B, it would be dangerous and incorrect, since the object will be reset when the constructor of the derived class is called. However, formA invokes the copy constructor of the base class. It would be better to call FormA. Similarly, in a redirection assignment statement, it is better not to call the assignment operator of the base class, and then the base class.

+5
source share
1 answer

Form A is incorrect. It does not implement the semantics of displacement. Regarding the version of Form B , the statement that " d not valid Base(std::move(d)) " is inaccurate. The exact operator must be "the Base part (subobject) d is nullified."

In addition, I suggest that you explicitly use d for the base type before calling 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 an explicit cast, you will get infinite recursion due to the constructor (5) std::function .

+3
source

All Articles