c++ - move 构造函数和多重继承

标签 c++ c++11 multiple-inheritance move-semantics move-constructor

概要

当类使用多重继承时,如何安全地设计 move 构造函数?

详情

考虑以下场景:

struct T { };
struct U { };

struct X : public T, public U
{
    X(X&& other)
      : T(std::move(other))
      , U(std::move(other)) // already moved?!
    {
    }
};

有没有办法安全地 move 构造 TU

最佳答案

tl;dr:问题中的代码没问题。

上面的代码很好,因为 std::move 本身实际上并没有以任何方式改变 other,它只是做了一个转换来使 other 到右值引用中,以便调用 TU 的 move 构造函数而不是它们的复制构造函数。

T(std::move(other)) 运行时,T 的 move 构造函数将被调用(假设它有一个)并且 other 中的T 将被 move 到this 中的Tother 中的 U 将保持独立,直到 U(std::move(other)) 运行。

请注意,这意味着当您的 X move 构造函数代码运行时,您不能依赖 TU 的成员/成员函数> 在 other 中,因为 other 的那些位已经被 move 了。


附带说明,可以通过更改为:

X(X&& other)
  : T(std::move(static_cast<T&>(other)))
  , U(std::move(static_cast<U&>(other)))
{
}

因为这个版本不依赖从 X&&T&&/U&& 的隐式向上转换。依赖于隐式向上转换可能是一个问题,因为 T 和/或 U 可能有一个 T(X&&) 构造函数或一个接受任何模板构造函数,其中任何一个都会被选中,而不是您真正想要调用的 T(T&&) move 构造函数。

关于c++ - move 构造函数和多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10114701/

相关文章:

c++ - 无法将带有 bool 网格的文本文件读入 vector 的 vector 中

ios - 使用 CoreData 保存 EVObject

php - CodeIgniter 扩展多个 Controller ?

c++ - 如何在 C++11 中初始化(通过初始化列表)多维 std::array?

c++ - C++中一些基本的继承问题

c++ - QWidget继承的类如何创建线程?

c++ reinterpret_cast、虚拟和模板好吗?

已知大小typedefed数组的c++函数模板特化

C++ 模板歧义

c++ - 如何使用 boost::bind 从参数中动态提取数据