Search code examples
c++c++14shared-ptr

how to extract data from refernce of shared_ptr<T&>


This is my function definition

void subscribe(std::shared_ptr<StrategyOrderEvents &> &strategy)
{
     auto p=make_pair(strategy.get()->m_StrategyName,strategy);
}

but when I'm trying to do strategy.get() I am getting the following error:

‘class std::shared_ptr’ has no member named ‘get’

inside the StrategyOrderEvents class, I have a data member name and I wont to extract it

*Edit Notice the get()->get() was a try i fix that to strategy.get()->m_StrategyName


Solution

  • You are not allowed to form shared (or other) pointers to references.

    Either do

    void subscribe(std::shared_ptr<StrategyOrderEvents>& strategy)
    

    or do

    void subscribe(StrategyOrderEvents& strategy)
    

    (and preferably add const correctness).

    You are currently accepting a reference to a shared pointer to a reference to an object. That's already way too many references from a code design standpoint (but the compiler only complains because forming a pointer to reference is illegal).

    The error message is not helpful, but your C++ implementation presumably implements the std::shared_ptr template in a way that leaves it as an empty class when instantiated with a reference type, somewhat like

    template<class T>
    class shared_ptr {
        // real implementation
    };
    
    template<T>
    class shared_ptr<T&> {}; // empty class for invalid usage