使用 std::move 实现 "take" 方法
Using std::move for a "take" method implementation
我想实现一个 "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;
};
None 个。我会用这个:
struct B
{
A && get() && { return std::move(m_a); }
};
这样你只能 "take" 来自 B
:
的右值
B b;
A a = std::move(b).get();
我想实现一个 "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;
};
None 个。我会用这个:
struct B
{
A && get() && { return std::move(m_a); }
};
这样你只能 "take" 来自 B
:
B b;
A a = std::move(b).get();