这里是一个最小的例子:
源代码:
#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
实际上,我想知道为什么原始输出中的第二行说'no'?我认为,当我们第一次创建类型为A的对象时(恰好在其构造完成之后,并且在我们对其调用grow()
之前),我们有一个有效的对象,可以将引用传递给我们想要的任何地方,不是吗?
从cppreference,关于std::enable_shared_from_this::weak_from_this
返回由引用
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
跟踪第一个对象。