C ++ weak_ptr expire after dereferencing?

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 ?

+4
3

A weak_ptr , shared_ptr, .

,

node d = *foo();

foo() a shared_ptr, shared_ptr, ( foo). shared_ptr , , . 0 weak_ptr.

shared_ptr , , . , , , undefined.

d shared_ptr node, node , .

+6
node d = *foo();

foo a shared_ptr, node, foo .

d, shared_ptr, . shared_ptr, node, foo, .

: shared_ptr.

+3

:

node d = *foo();

shared_ptr, d node, foo :

shared_ptr<node> a = make_shared<node>();

a node d = *foo();. , _ptr node.

, ( )?

, , .

You can switch from weak_tr<node> parent;to shared_ptr<node> parent;. Another solution is to keep global shared_ptr<node> root;, which will keep the link to yours a. But it depends on what your code is really going to do.

+2
source

Source: https://habr.com/ru/post/1649110/


All Articles