Boost :: shared_ptr created using this

Consider the following case:

typedef boost::shared_ptr<B> BPtr;

class A
{
public:
    A() { b_ptr = BPtr(new B); }
    void a_func() { C::c_func(b_ptr); }
private:
    BPtr b_ptr;
}

class B
{
public:
    B() { b_ptr = BPtr(this); }
    void b_func() { C::c_func(b_ptr); }
private:
    BPtr b_ptr;
}

class C
{
public:
    static void c_func(BPtr b_ptr) { /*...*/ }
}

Is it possible to create an instance of shared_ptr with this?
Is it possible to have two shared_ptr objects pointing to the same object? (for example, A :: b_ptr and B :: b_ptr)
If one of these two goes out of scope, is instance B deleted?

I assume that I am doing something fundamentally wrong.
I also thought about using b_ptr dependency injection on constructor B, but that seems very wrong too.

UPDATE:
- A, B C:: c_func. , C B, . :

  • , C , BPtr A, B, .
  • C A B C, BPtr C ctor.
+3
2

shared_ptr ?

, :

  • A B , shared_ptr "" , ; , shared_ptr, delete , Bad Things Happen. , , , : auto_ptr, .

  • . , b_ptr B, . .reset() , B .

shared_ptr this enable_shared_from_this, : enable_shared_from_this . , shared_ptr ; .

, - .

, , , , . , , , .

+10

std:: enable_shared_from_this, .

class B
{
   B();
public:
   std::shared_ptr<B> create() { return std::make_shared<B>(); } // Make sure B is allocated as shared_ptr inorder to ensure that shared_from_this() works.
};

, API, ( ).

void b_func() { C::c_func(BPtr(this, [](B*){})); } // Empty deleter. Nothing happens when shared_ptr goes out of scope. Note that c_func cannot take ownership of the pointer.
0

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


All Articles