我开始学习shared_ptr 和weak_ptr。从理论上讲,一切看起来都很简单。但是当我开始测试时,嗯......我有这个非常简单的程序:
#include <iostream>
#include <memory>
using namespace std;
class Second
{
public:
Second()
{
cout << "Second created" << endl;
}
~Second()
{
cout << "Second deleted" << endl;
}
};
class Main
{
public:
shared_ptr<Second> second;
Main()
{
cout << "Main created" << endl;
second = make_shared<Second>(*(new Second()));
}
~Main()
{
second.reset();
cout << "Main deleted" << endl;
}
};
void fun()
{
shared_ptr<Main> main = make_shared<Main>(*(new Main()));
}
int main()
{
cout << "Program started" << endl;
fun();
cout << "Program ended" << endl;
return 0;
}
问题是,Second 永远不会被删除。这是我的输出:
Program started Main created Second created Main deleted Program ended
这是怎么回事?我想,如果我重置 shared_ptr,并且它的最后一个 shared_ptr 存在,对象会自动删除。