Search code examples
c++pointersshared-ptr

using a shared_ptr object in constructor works but not in destructor


I have a class where the construction is like:

class CLSS
{
public:
    CLSS(const std::shared_ptr<someType>& pobj) 
    {
    std::shared_ptr<someType> obj = pobj;
    obj->somefunc("DDDD")
    }
    ~CLSS()
    {
    }
};

which works with now problem. However when I put the same function of obj->info("DDDD") in the diconstructor, it returns error, that is:

    ...
    ~CLSS()
    {
      obj->info("DDDD")
    }
    ....

---------------edit

I tried

class CLSS
{
public:
    std::shared_ptr<someType> obj;

    CLSS(const std::shared_ptr<someType>& pobj) 
    {
    obj = pobj;
    obj->somefunc("DDDD")
    }
    ~CLSS()
    {
    }
};

but still does not compile, the errors are not very readble.


Solution

  • obj is a local variable in the constructor. It is destroyed when the constructor ends. You need to declare it as a member of your class.