【发布时间】:2016-07-26 04:50:18
【问题描述】:
我是智能指针的新手,我想弄清楚为什么weak_ptr 在取消引用运算符之后会过期。我用来测试的代码在这里:
#include <memory>
#include <iostream>
#include <vector>
using namespace std;
struct node
{
weak_ptr<node> parent;
shared_ptr<node> child;
int val;
};
shared_ptr<node> foo()
{
shared_ptr<node> a = make_shared<node>();
shared_ptr<node> b = make_shared<node>();
a->val = 30;
b->val = 20;
b->parent = a;
a->child = b;
return a;
}
int main()
{
shared_ptr<node> c = foo();
node d = *foo();
if (c->child->parent.expired())
{
cout << "weak ptr in c has expired." << endl;
}
if (d.child->parent.expired())
{
cout << "weak ptr in d has expired." << endl;
}
return 0;
}
程序输出weak ptr in d has expired.
我不明白为什么当d 使用解引用运算符时,它会过期。关于这一点,有没有办法阻止它(除了不取消引用它)?
我通过将节点中的weak_ptr 更改为shared_ptr 来尝试as mrtnj suggested,但我认为我有内存泄漏。我将node 类更改为
struct node
{
shared_ptr<node> parent;
shared_ptr<node> child;
int val;
};
然后修改源代码添加了tryCreate函数。
void tryCreate()
{
node d = *foo();
}
然后在我的 main 中调用它,这样我的 main 看起来像
int main()
{
tryCreate();
return 0;
}
我使用了 Visual Studio 2015 的内存分析,发现只有分配,没有释放。我将parent 更改为weak_ptr,我看到了释放。我做错了什么还是确实需要在这些循环条件下使用weak_ptr?
【问题讨论】:
标签: c++ smart-pointers weak-ptr