Search code examples
c++boostshared-ptr

will the shared_ptr be deleted if i delete the class


I have a class like this :

Header:

class CurlAsio {
public:
    boost::shared_ptr<boost::asio::io_service> io_ptr;
    boost::shared_ptr<curl::multi> multi_ptr;
    CurlAsio();
    virtual ~CurlAsio();
    void deleteSelf();
    void someEvent();
};

Cpp:

CurlAsio::CurlAsio(int i) {
    id = boost::lexical_cast<std::string>(i);
    io_ptr = boost::shared_ptr<boost::asio::io_service>(new boost::asio::io_service());
    multi_ptr = boost::shared_ptr<curl::multi>(new curl::multi(*io_ptr));
}

CurlAsio::~CurlAsio() {
}

void CurlAsio::someEvent() {
  deleteSelf();
}

void CurlAsio::deleteSelf() {
    if (io_ptr) {
        io_ptr.reset();
    }
    if (multi_ptr)
        multi_ptr.reset();
    if (this)
        delete this;
}

During run time, many instances of CurlAsio Class is created and deleted.

So my questions are:

  1. even though I am calling shared_ptr.reset() , is it necessary to do so ?
  2. i monitor the virtual memory usage of the program during run time and I would expect the memory usage would go down after deleteSelf() has been called, but it does not. Why is that?
  3. if i modify the deleteSelf() like this:

    void CurlAsio::deleteSelf() {
    
        delete this;
    
    }
    

What happens to the two shared pointers ? do they get deleted as well ?


Solution

  • The shared_ptr members have their own destructor to decrement the reference count on the pointee object, and delete it if the count reaches 0. You do not need to call .reset() explicitly given your destructor is about to run anyway.

    That said - why are you even using a shared_ptr? Are those members really shared with other objects? If not - consider unique_ptr or storing by value.

    As for memory - it doesn't normally get returned to the operating system until your program terminates, but will be available for your memory to reuse. There are many other stack overflow questions about this.

    If you're concerned about memory, using a leak detection tool is a good idea. On Linux for example, valgrind is excellent.