Please help, .lock() doesn't work

I learn smart pointers. And right now I am learning reference loop. I found some code in net and changed it, but it doesn't work. Please help. Function .lock() does nothing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>

class B;

class A
{
public:
    A() {}
    boost::weak_ptr<B> b;
};

class B
{
public:
    B() {}
    boost::shared_ptr<A> a;
};

int main()
{
    boost::shared_ptr<A> _A(new A); // A == 1
    boost::shared_ptr<B> _B(new B); // B == 1

    std::cout << "Created" << std::endl;
    std::cout << "A " << _A.use_count() << std::endl; // A == 1
    std::cout << "B " << _B.use_count() << std::endl; // B == 1

    _A->b = _B; // B != +1
    _B->a = _A; // A +1

    std::cout << "Increased" << std::endl;
    std::cout << "A " << _A.use_count() << std::endl; // A == 2
    std::cout << "B " << _B.use_count() << std::endl; // B == 1

    _B = _A->b.lock(); // B +1 if I will need it
    
    std::cout << "Locked" << std::endl;
    std::cout << "A " << _A.use_count() << std::endl; // A == 2
    std::cout << "B " << _B.use_count() << std::endl; // B == 1, but should be 2

    return 0;
}
  
_B = _A->b.lock();

This doesn't really do anything because _B and _A->b are already pointing to the same object. Only one shared_ptr points to the object so use_count() returns 1 as expected.
As I understood, lock() increases use_counter() when shared_ptr and weak_ptr point to another objects?
lock() returns a temporary shared_ptr object. When this object is created the use count is increased by 1 because there is now one more shared_ptr pointing to the object.

The temporary shared_ptr object is then assigned to _B. The use count of the object pointed to by _B before the assignment will be decreased by 1 (if it drops to 0 it will be deleted) and then the use count of the assigned object will be increased by 1. In this case _B points to the same object before and after so the use count stays the same (-1+1=0).

At the end of the line the temporary shared_ptr object is destroyed so the use count is decreased by 1.

In total the use count didn't change.
Last edited on
Peter87, thanks man, you really helped!
Last edited on
Topic archived. No new replies allowed.