I'm new to smart pointers, and I'm trying to wrap myself around why weak_ptr will expire after the dereference operator. The code I used for testing is here:
#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;
}
Program outputs weak ptr in d has expired.
I don’t understand why when it duses the dereference operator, it expires. As for this, is there a way to prevent it (other than dereferencing it)?
I tried as mrtnj suggested , changing weak_ptrnode to shared_ptr, but I think I have a memory leak. I changed the class nodeto
struct node
{
shared_ptr<node> parent;
shared_ptr<node> child;
int val;
};
and then changed the source code to add a function tryCreate.
void tryCreate()
{
node d = *foo();
}
and then called it in mine main, so my main function looks like
int main()
{
tryCreate();
return 0;
}
Visual Studio 2015 , . parent weak_ptr, . - weak_ptr ?