是否可以从move构造函数调用默认构造函数?

时间:2019-09-03 18:24:49

标签: c++

我正在实现move构造函数,并且需要将其他构造函数初始化回其默认状态,就像在默认构造函数中实现的一样。这可能吗,还是我需要复制代码?

class Class
{
  Class() { /* code to duplicate */ }
  Class(Class&& other) :
    mMember(other.mMember) {
    other.Class(); // code to duplicate?
  }
};

我知道other.Class()在这里无效,我知道构造函数现在可以使用C ++ 11相互调用。

1 个答案:

答案 0 :(得分:4)

最好的方法是重新分配它。由于该对象已被构造,因此再次调用该构造函数将是一个错误。

但是,您可以创建一个实例并调用赋值运算符:

Class(Class&& other) noexcept : mMember(std::move(other.mMember)) {
    other = Class{};
}

另一种方法是默认构造您的类并与旧的交换值:

Class(Class&& other) noexcept {
    std::swap(mMember, other.mMember);
}

如果您确实需要other来获取调用默认构造函数所需的值,则可以执行以下操作:

Class(Class&& other) noexcept : Class() {
    std::swap(mMember, other.mMember);
}

它将在新对象中调用默认构造函数,然后交换other对象中的值。