【发布时间】: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;
};
【问题讨论】:
-
为什么要放在B里面?
-
我认为不是完全重复,但另请参阅stackoverflow.com/q/29504070/1858225
-
我建议将
take重命名为release,因为此名称在智能指针中用于类似目的:en.cppreference.com/w/cpp/memory/unique_ptr/release -
我现在知道恐惧了。谢谢,伙计。
标签: c++ c++11 move move-semantics