Search code examples
c++singletonc++17smart-pointersunique-ptr

access the unique pointer across the class without using reference or shared pointer


Posting Again, Unique pointer stored in class A, need to access in class B without using shared ptr or reference?. (ie)The owner of that pointer should remain only in class A and the semantic ownership of the pointer should not be shared. func1, func2, func3 all the places unique pointer is accessed many times. code snip helps, I am new to smart pointers.

class A
{
public:
    static A* Get();
    A();
    virtual ~A();
    std::unique_ptr<ABC> *Getter();
private:
    std::unique_ptr<ABC> uniquePointer;
}   

A.cpp

A::A() 
{
   uniquePointer = std::unique_ptr<ABC> new ABC();
}

A::Getter()
{
   return &uniquePointer; => This worked but it is not desirable.
}

b.h

#include <a.h>
class B {
private:
    func1();
    func2();
    func3();
}

B.cpp

B::func1()
{
    std::unique_ptr<ABC> *getPtrfunc1 = A::Get()->Getter();
}
B::func2()
{
    std::unique_ptr<ABC> *getPtrfunc2 = A::Get()->Getter();
}
B::func3()
{
    std::unique_ptr<ABC> *getPtrfunc3 = A::Get()->Getter();
}

Solution

  • the semantic ownership of the pointer should not be shared

    Don't don't pass around access to the unique_ptr at all. Pass around a raw pointer to the ABC that the unique_ptr owns, eg:

    class A
    {
    public:
        static A* Get();
        A();
        ABC* Getter();
    private:
        std::unique_ptr<ABC> uniquePointer;
    };
    
    A::A() 
    {
       uniquePointer = std::make_unique<ABC>();
    }
    
    A* A::Get()
    {
        static A a;
        return &a;
    }
    
    ABC* A::Getter()
    {
       return uniquePointer.get();
    }
    
    #include <a.h>
    
    class B {
    private:
        void func1();
        void func2();
        void func3();
    }
    
    void B::func1()
    {
        ABC *getPtrfunc1 = A::Get()->Getter();
    }
    
    void B::func2()
    {
        ABC *getPtrfunc2 = A::Get()->Getter();
    }
    
    void B::func3()
    {
        ABC *getPtrfunc3 = A::Get()->Getter();
    }