在返回语句之前,从派生类中调用基类移动赋值运算符的正确位置是第一个语句还是最后一个语句?
我在Base和Derived中有成员,需要将其作为移动分配运算符的一部分进行移动。
Class Base {
// Members goes here
public:
Base &operator=(Base &&o) {
// move all the members specific to the class here
return *this;
}
};
class Derived {
// Members goes here
public:
Derived &operator=(Derived &&o) {
// Is this correct? Base class move here or below?
Base::operator=(std::move(o));
// move all the members specific to the class here
// The assumption is that once we use move we cannot use the variable.
// So, should I have base class move call here? Base::operator(std::move(o));
return *this;
}
};
对您的语义来说是正确的。通常,使用默认移动分配是正确的:
Derived &operator=(Derived &&o) = default;
默认实现将从基数开始。
但是如果您自己定义移动,则可能有一个原因,并且这个原因可能会指示不同的顺序。
甚至可能根本不需要打基础,而做一些完全不同的事情。例如,这种需求可能来自所需的异常安全保证。