【问题标题】:To write a move assignment operator for a trivial derived class [duplicate]为平凡的派生类编写移动赋值运算符[重复]
【发布时间】:2014-08-04 00:12:22
【问题描述】:

我想知道在以下情况下如何编写移动赋值运算符:

class Foo : public vector<int>
{
public:
  Foo(Foo&& other) : vector<int>(move(other)) {};
  Foo& operator=(Foo&& other){ ????? };
};

效果如何?

谢谢, 汤姆

【问题讨论】:

  • 推荐从 STL 继承的特殊情况。这不是一个。
  • 派生的类是无关紧要的,除了它应该是可复制和可移动的。
  • 你说得对,它是重复的。我想我的问题更短更直接,但它仍然是重复的。
  • Foo&amp; operator = (Foo&amp;&amp;) &amp; = default;

标签: c++ c++11 move-semantics assignment-operator


【解决方案1】:
class Foo
    : public vector<int>
{
public:
    auto operator=( Foo&& other )
        -> Foo&
    {
        vector<int>::operator=( move( other ) );
        return *this;
    };

    Foo( Foo&& other )
        : vector<int>( move( other ) )
    {};
};

或者只是

class Foo
    : public vector<int>
{
public:
    auto operator=( Foo&& other ) -> Foo& = default;

    Foo( Foo&& other )
        : vector<int>( move( other ) )
    {};
};

我不确定自动生成移动赋值运算符的规则,目前还不依赖编译器正确实现这些规则(截至 2014 年 6 月)。

【讨论】:

  • 为什么要使用替代函数声明语法?有关系吗?
  • 相反,因为这是涵盖所有情况的唯一语法,所以它是主要语法。旧语法是替代语法,仅支持功能子集。为什么要使用任意组合的语法,而不是到处使用主要的语法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 2017-11-21
  • 2016-01-28
  • 1970-01-01
  • 2013-10-07
  • 2012-02-12
  • 2020-02-16
相关资源
最近更新 更多