【发布时间】:2020-09-01 04:02:39
【问题描述】:
以下是我正在尝试的玩具代码...我理解第一个和第二个。第一个将所有权授予_p。第二个将p 复制到_p。
但是第三个没看懂……
const shared_ptr & 中的std::move 是什么意思?谢谢。
class P { };
class A {
public:
// first one
A(std::shared_ptr<P> &p, int) : _p(std::move(p))
{
std::cout << "1st Ctor: "
<< p.use_count() << ", " << _p.use_count() << std::endl;
}
// second one
A(const std::shared_ptr<P> &p, std::string) : _p(p)
{
std::cout << "2nd Ctor: "
<< p.use_count() << ", " << _p.use_count() << std::endl;
}
// third one
A(const std::shared_ptr<P> &p) : _p(std::move(p))
{
std::cout << "3rd Ctor: "
<< p.use_count() << ", " << _p.use_count() << std::endl;
}
private:
std::shared_ptr<P> _p;
};
int main()
{
{
std::shared_ptr<P> p = std::make_shared<P>();
A a(p, 1);
std::cout << "1. body: " << p.use_count() << std::endl;
}
std::cout << "-------------" << std::endl;
{
std::shared_ptr<P> p = std::make_shared<P>();
A a(p, "2");
std::cout << "2. body: " << p.use_count() << std::endl;
}
std::cout << "-------------" << std::endl;
{
std::shared_ptr<P> p = std::make_shared<P>();
A a(p);
std::cout << "3. body: " << p.use_count() << std::endl;
}
}
结果是:
$ ./a.out
1st Ctor: 0, 1
1. body: 0
-------------
2nd Ctor: 2, 2
2. body: 2
-------------
3rd Ctor: 2, 2
3. body: 2
(更新:添加注释以阐明哪个是第一个,第二个等)
【问题讨论】:
-
你可能应该更清楚你所说的“第一个”是什么意思(第一行,第一个块,第一次调用
std::move?)。这同样适用于您的问题:“std::moveofconst shared_ptr &”是什么意思?引用特定的行。 -
在我的团队中,第 1 次、第 2 次和第 3 次在代码审查中都会被视为不好的做法。对于转移所有权
A(std::shared_ptr<P>&& p)(这对于 shared_ptr 来说有点奇怪)或A(std::shared_ptr<P> p)(任何接收器参数的典型模式)将是表达意图的方式。 -
@Eljay,感谢您的评论。您的建议使用起来更清楚。根据您的评论,我发现
const shared_ptr &在复制/移动方面似乎有些模棱两可。 -
@eric
const shared_ptr &明确表示不适合搬家。
标签: c++ c++11 shared-ptr move-semantics stdmove