C++ 那么,现在基本类是如何用C++;11?

C++ 那么,现在基本类是如何用C++;11?,c++,c++11,class-design,move-semantics,rvalue,C++,C++11,Class Design,Move Semantics,Rvalue,更新:我使用MSVC10,它没有给我默认的移动语义 假设我想创建一个包含两个非pod成员的常规类 class Foo { NonPodTypeA a_; NonPodTypeB b_; } 像往常一样,我实现了一个复制构造函数和一个赋值运算符,在其中我使用了复制构造函数: Foo(const Foo& other) : a_(other.a_), b_(other.b_) {} Foo& operator=(const Foo& other) { Foo cons

更新:我使用MSVC10,它没有给我默认的移动语义

假设我想创建一个包含两个非pod成员的常规类

class Foo {
NonPodTypeA a_;
NonPodTypeB b_;
}
像往常一样,我实现了一个复制构造函数和一个赋值运算符,在其中我使用了复制构造函数:

Foo(const Foo& other) : a_(other.a_), b_(other.b_) {}
Foo& operator=(const Foo& other) { 
  Foo constructed(other);
  *this = std::move(constructed);
  return *this;
}
然后我实现了move构造函数和move赋值,它对所有成员使用std::swap而不是std::move,因为它们可能是在move语义可用之前编写的,在实现move语义时,我可以省略实现swap成员函数:

Foo(Foo&& other) {
  ::std::swap(a_, other._a);
  ::std::swap(b_, other._b);
}
Foo& operator=(Foo&& other) { 
  ::std::swap(a_, other._a);
  ::std::swap(b_, other._b);
  return *this;
}
我的问题来了假设我对成员一无所知,这里可以做些更一般的事情吗?

例如,move构造函数与const声明的成员不兼容,但是如果我将move构造函数实现为
Foo(Foo&&other):a_uz(std::move(other.a_z)),b_z(std::move(other.b_z)){}
我不能确保没有移动语义的类不会被复制? 我能以某种巧妙的方式在移动赋值中使用移动构造函数吗?

呃,什么都不做。所有这些都是为您自动生成的1。您需要手工编写它们的唯一时间是在类处理资源时(然后您需要遵循)。这也正是以前的情况。现在唯一的区别是,在考虑了三个规则之后,出于语义(即仅移动对象)或性能(移动通常比复制快)的原因,您可能希望实现移动成员



一,。MSVC 10不会自动生成移动构造函数。在这种情况下,您可能希望自己编写移动成员:(

鉴于MSVC10和MSVC11的局限性,您必须编写自己的移动构造函数/移动分配操作符,以下是我所拥有的。我基于Stephan T.Lavavej的此视频


像往常一样,你什么也没有实现。让a和b自己去做。这样做的错误多于正确。除此之外,不要完全限定
std::swap
。ADL应该用来调用
swap
,而不是显式限定(除非该限定是
boost::swap
,它将在内部使用ADL).ildjarn:我仍然不明白,如果在类中实现了移动语义,std::swap将使用它(至少在MSVC10中)@ViktorSehr:不允许向
命名空间std
添加重载。这就是为什么要从ADL命名空间中选择
swap
。“MSVC 10不会自动生成移动构造函数,但这是MSVC 11中缺少的一项功能。”这不是我的理解。你手头有验证这一点的链接吗?它不会添加到VC11中。请按照VC 11.1的思路多想想。@ildjarn oops,我感到困惑。看来它毕竟不在VC11中:(
class Foo 
{
public:

    //Note: don't pass param by reference. Unified assignment operator
    Foo& operator=(Foo other)
    {
        other.swap(*this);
        return *this;
    }

    Foo(Foo&& other)
      : a_(std::move(other.a_),
        b_(std::move(other.b_){}

    Foo(Foo& other)
      : a_(other.a_),
        b_(other.b_){}

private:
    void swap(Foo& other)
    {
        using std::swap;
        swap(a_, other.a_);
        swap(b_, other.b_);
    }

private:
    NonPodTypeA a_;
    NonPodTypeB b_;
};