我有以下一段代码,它正在创建一个简单的Name对象,并在其中创建另一个对象Name,具有shared_from_this()
引用。正如我从这里读到的https://en.cppreference.com/w/cpp/memory/enable_shared_from_this/shared_from_this
"有效执行std::shared_ptr(weak_this),其中weak_this是enable_shared_from_this的私有可变std::weak_ptr成员。">
我理解为shared_from_this()只是创建一个指向共享对象的弱指针。但我不认为这是运行时的情况。有有效地创建一个循环引用。
在结束时,我期望Name对象应该被销毁,但它没有,因为引用计数器是2。
有人能帮助我理解我应该如何使用enable_shared_from_this()
,这可以有效地清理名称obj,一旦它超出引用范围。
#include <iostream>
#include <memory>
#include <string>
#include <chrono>
#include <thread>
using namespace std;
struct Another;
struct Name : public std::enable_shared_from_this<Name> {
std::string t;
int m, n, p;
shared_ptr<Another> ann;
Name() {
std::cout << "constructorn";
}
void MakeSomething() {
ann = std::make_shared<Another>(shared_from_this());
}
~Name() {
std::cout << "destructorn";
}
};
struct Another {
shared_ptr<Name> nn;
Another(shared_ptr<Name> n) : nn(n) {
std::cout << "from another constructor " << nn.use_count() << "n";
}
~Another() {
std::cout << "from another destructorn";
}
};
int main()
{
{
auto n = std::make_shared<Name>();
std::cout << "Name ref count so far: " << n.use_count() << "n";
auto p = n.get();
//delete p;
std::cout << "Name ref count so far: " << n.use_count() << "n";
n->MakeSomething();
std::cout << "Name ref count so far: " << n.use_count() << "n";
{
shared_ptr<Name> m = n;
std::cout << "Name ref count so far: " << n.use_count() << "n";
}
std::cout << "Name ref count so far: " << n.use_count() << "n";
}
// problem: at this point Name obj, should go out of reference and destructor to be called, which is NOT happening
return 0;
}
下面是运行时输出(编译器使用msvc)
constructor
Name ref count so far: 1
Name ref count so far: 1
from another constructor 3
Name ref count so far: 2
Name ref count so far: 3
Name ref count so far: 2
我理解为shared_from_this()只是创建一个指向共享对象的弱指针。但我不认为这是运行时的情况。这实际上是创建了一个循环引用。
shared_from_this()
正在创建weak_ptr
,您将其传递给shared_ptr
构造函数,如此处(11)所指定的。该构造函数为同一对象创建了一个shared_ptr
,增加了引用计数。
还请记住,weak_ptr
并不导致引用计数,所以它没有影响你的困惑在引用计数。关注shared_ptr
在做什么。