移动构造函数和多重继承 [英] Move constructors and multiple inheritance

查看:75
本文介绍了移动构造函数和多重继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I safely design a move constructor when a class uses multiple inheritance?

请考虑以下情形:

struct T { };
struct U { };

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

是否可以安全地移动构造 T U ?

Is there a way to move-construct both T and U safely?

推荐答案

tl; dr :问题中的代码还可以.

tl;dr: the code in the question is ok.

上面的代码很好,因为 std :: move 本身实际上不会以任何方式更改 other ,它只是进行强制转换以使 other放入右值引用,以便调用 T U 的move构造函数,而不是其复制构造函数.

The code above is fine, because std::move itself doesn't actually change other in any way, it just does a cast to make other into an rvalue reference so that the move constructors of T and U are called instead of their copy constructors.

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

When T(std::move(other)) is run, T's move constructor will be called (assuming it has one) and the T in other will be moved to the T in this. The U in other will be left alone until the U(std::move(other)) is run.

请注意,这意味着当您运行 X 的移动构造函数代码时,您不能依赖 T U 在 other 中,因为 other 的那些位将已经被移动.

Note that this means that when your move constructor code for X runs, you cannot rely on the members/member functions of T and U in other, as those bits of other will have already have been moved.

请注意,可以更改为:

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&&)移动构造函数.

because this version doesn't rely on the implicit upcast from X&& to T&&/U&&. Relying on the implicit upcast can be a problem because T and/or U may have a T(X&&) constructor or an accept-anything template constructor, either of which would get picked instead of the T(T&&) move constructor that you really want to call.

这篇关于移动构造函数和多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆