Ownership sharing with smart pointers while object initialization

54 views Asked by At

I have a class A that has a member pointer to class B:

class A 
{
public: 
    A() 
    {
        m_b = createB();
    }
    std::shared<B> getSpB()
    {
        return m_b;
    }
private:
    std::shared<B> m_b;
};

class B 
{
public: 
    B() {}

    static std::shared_ptr<B> createB()
    {
        return std::make_shared<B>();
    }
    void func1() {/* ... */ }

private:
};

In my main function I create a shared_ptr of class A and then use some methods of both classes.

int main() 
{
    auto spA = std::make_shared<B>();
    auto spB = spA->getSpB();

    spA.reset();
    spB->func1();
}

However before using the method of B, func1(), I would like to reset the spA pointer. But the object spA is pointing to, is not allowed to be destroyed yet (design requirement, because object pointed by spB can hold references on some of the A's members).

To be able to do that I thought that B can also hold a pointer to A, lets say A* m_A. But since B is created from A's constructor, there is no A object yet to initialize m_A.

Passing this in A's constructor to createB(this) does not solve the problem, since it does not share ownership with spA, which is created in the first line of main(), so it does not prevent the object pointed by spA to be destroyed completely after spA.reset().

Another alternative I had, was to make m_A a shared_ptr, but passing shared_from_this() in A's constructor to createB(this->shared_from_this()) is either impossible, since the A object has not been created yet.

Do you have any suggestions how to solve this problem?

0

There are 0 answers