下面是一个可复制的最小示例:
源代码:
#include <memory>
#include <iostream>
class A : public std::enable_shared_from_this<A>
{
public:
A(std::weak_ptr<A> up) : up_(up)
{
std::cout << "A" << " has up_? " <<
((up_.lock()) ? "yes" : "no")
<< std::endl;
}
void grow()
{
if (dp_)
dp_->grow();
else
dp_ = std::make_shared<A>(weak_from_this());
}
private:
std::weak_ptr<A> up_;
std::shared_ptr<A> dp_;
};
int main()
{
auto wp = std::weak_ptr<A>();
A a(wp);
for (int i = 0; i < 3; ++i)
{
a.grow();
}
return 0;
}原始日志:
clang++ minimal.cpp && ./a.out
A has up_? no
A has up_? no
A has up_? yes
A has up_? yes期望的行为:
clang++ minimal.cpp && ./a.out
A has up_? no
A has up_? yes
A has up_? yes
A has up_? yes实际上,我想知道为什么原始输出中的第二行说“不”?我认为,当我们第一次创建A类型的对象时(在它的构造完成之后,在调用grow()之前),我们有一个有效的对象,我们可以将引用传递到任何我们想要的地方,不是吗?
发布于 2020-03-04 08:25:54
来自cp偏好,关于std::enable_shared_from_this::weak_from_this的
返回一个
std::weak_ptr<T>,它通过引用*this的所有现有std::shared_ptr来跟踪*this的所有权。
同时
A a(wp);这不是由任何shared_ptr跟踪的对象。它是一个具有自动存储持续时间的普通对象。如果希望weak_from_this工作,必须有跟踪第一个对象的shared_ptr。
https://stackoverflow.com/questions/60521636
复制相似问题