我想实现一个“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;
};
答案 0 :(得分:4)
他们都不是。我会用这个:
Username for 'https://github.com': jgoldstick
Password for 'https://jgoldstick@github.com':
Counting objects: 29, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (14/14), done.
Writing objects: 100% (16/16), 2.61 KiB | 0 bytes/s, done.
Total 16 (delta 12), reused 0 (delta 0)
To https://github.com/jgoldstick/baseball.git
7be5c2d..d324acb master -> master
fatal: Unable to create '/home/jcg/code/python/venvs/baseball/.git/refs/remotes/origin/master.lock': Permission denied
Unexpected end of command stream
(baseball)jcg@jcg:~/code/python/venvs/baseball$
这样你只能从struct B
{
A && get() && { return std::move(m_a); }
};
:
B