使用 std::move 实现"take"方法。

Using std::move for a "take" method implementation

本文关键字:take 方法 实现 std move 使用      更新时间:2023-10-16

我想实现一个"take"方法。"take"方法类似于get方法,但它从其所有者那里窃取getted对象:所有者使该对象处于空状态。当然,这涉及到 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;
};

都不是。我会用这个:

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

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

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