mercredi 5 juillet 2017

shared_pointer unexpected behaviour

There is piece of code:

A.cpp

class MySomeClass: public SomeClass
{
   public: 
   void specificMethod();
}

class A
{
    public:
    A::A();

    std::shared_ptr< B > m_bObject;
    std::shared_ptr< MySomeClass > m_argument;
}

A::A()
{
    m_argument= std::make_shared< MySomeClass >();
    m_bObject = std::make_shared< B >( m_argument);
}

B.cpp

B::B(const std::shared_ptr< SomeClass >& smartOne):m_smartOne(smartOne)
{}

B::someMethod()
{
    m_smartOne->specificMethod();
}

B.h

class B
{
public:
    B(const std::shared_ptr< SomeClass >& smarOne);
    void someMethod();

private:
    const std::shared_ptr< SomeClass >& m_smartOne;
};

Problem is when I call m_bObject->someMethod() there is a core dump because m_smartOne is not a MySomeClass but SomeClass.
But when m_smartOne will be not a member but local variable everithing is as expected. Why? Is it scope problem, ownership problem, other?
I've recieved code of B class and can't change it.

Aucun commentaire:

Enregistrer un commentaire