Marco Sanfilippo Marco Sanfilippo - 3 months ago 19
C++ Question

Circular buffer with smart_ptr and weak_ptr?

I can't find a complete example that shows how to eliminating strong circular references between

shared_ptr
.

Problem is how to use a
weak_ptr
to "close" the chain of generic elements and to access the "next" element with the
weak_ptr
.

Thank you.

EDIT:

For example, suppose to have
Element e1, e2, e3;
with pointer inside to the next element.
In C we do

e1->Next = e2;
e2->Next = e3;
e3->Next = e1;


...and we could do
e1->Next->Next->Next->Next->Next
etc.

In C++ with
shared_ptr
we cannot do the last
->Next = e1
because of circular references and destructor will not release all the
Element
.

We need a
weak_ptr
: but what type of operations for the same result?

Answer

Ok I found the solution.

When I need to access from the last to the first element of the chain (object, struct or typedef_data) simply use the weak_prt with lock() (maybe with expired() to check if poiter still exists...)

Example:

 std::weak_ptr<int> gw;

void f()
{
    if (auto spt = gw.lock()) { // Has to be copied into a shared_ptr before usage
    std::cout << *spt << "\n";
}
else {
        std::cout << "gw is expired\n";
    }
}

int main() {

{ //into the scope
    auto sp = std::make_shared<int>(42);
    gw = sp;

    f();
}
 // out of the scope
f();
}

So, output will be:

42
gw is expired

expired() is not used in this example but should be used before lock() and the return value of lock() MUST BE always checked.