【问题标题】:Using std::move for a "take" method implementation使用 std::move 实现“take”方法
【发布时间】:2016-02-05 17:05:49
【问题描述】:

我想实现一个“take”方法。 “take”方法类似于 get 方法,但它会从其所有者那里窃取获取的对象:所有者留下的对象处于空状态。 当然,这涉及到 C++11 的移动语义。 但以下哪项是最好的实施方式?

class B
{
public:

    A take_a_1()
    {
        return std::move(m_a);
    }

    // this can be compiled but it looks weird to me that std::move 
    // does not complain that I'm passing a constant object
    A take_a_2() const
    {
        return std::move(m_a);
    }

    A&& take_a_3()
    {
        return std::move(m_a);
    }

    // this can't be compiled (which is perfectly fine)
    //
    // A&& take_a_4() const
    // {
    //     return std::move(m_a);
    // }

private:

    A m_a;
};

【问题讨论】:

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


【解决方案1】:

没有。我会用这个:

struct B
{
    A && get() && { return std::move(m_a); }
};

这样你只能从B的右值中“取”:

B b;
A a = std::move(b).get();

【讨论】:

  • 这很有趣。你能解释一下为什么只取整个 B 对象的右值更好吗?
  • @nyarlathotep108:好吧,如果对象本身不再可观察(即右值),那么将对象留在残缺状态似乎是无条件可取的。否则,您将不得不指定获取如何工作以及剩余对象如何行为的详细语义。
  • @nyarlathotep108 另外,至关重要的是,由于m_aB 的一部分,并且对象的状态仅保证在移出后可破坏(什么都没有保证),Bm_a移出后的状态是这样的,唯一的安全操作是破坏。使对象状态无效的函数通常应该只采用该对象的 R 值,以便从接口中可以明显看出这种状态无效。
猜你喜欢
  • 2016-06-24
  • 2013-03-30
  • 2021-01-05
  • 1970-01-01
  • 2015-05-03
  • 1970-01-01
  • 2019-07-09
  • 2016-10-27
  • 1970-01-01
相关资源
最近更新 更多