c++shared-ptrmake-shared

Why make_shared call the destructor even if there are still weak pointer?


From theory, one difference between make_shared() and shared_ptr is the memory allocation technique. make_shared() should use a single block, while shared_ptr should use two blocks.

One make_shared() drawback should be that memory can't be freed if there is even a single weak_ptr alive.

Can someone explain why the output of this program is always the same independently from the function I use to create the shared_ptr?

#include <iostream>
#include <memory>

class mc
{
    public:
      mc(int p):p_{p} {std::cerr<<"Constructor"<<std::endl;}
      ~mc() { std::cerr<<"Destructor"<<std::endl;}    
    private:
      int p_;    
};

std::weak_ptr<mc> wp3;

int main()
{
 
    auto sp=std::make_shared<mc>(4);
    auto sp2=sp;
    auto sp3{sp};
    wp3=std::weak_ptr<mc>{sp};
    
    sp2.reset();
    sp3.reset();
    sp.reset();
     
    for (int i =0;i< 5;i++) {std::cerr<<sp.use_count()<<std::endl;}   

    return 0;
}

I was expecting the destructor method to be called at the end, since the weak_ptr is still alive, why is that not happening?


Solution

  • Even if its memory can't be freed, the object held by a shared_ptr will still be destroyed when the (non-weak) refcount reaches zero. Object destruction and memory release are two separate operations that don't need to happen at the same time.

    In general, since the "one allocation" behavior of make_shared is an optimization, it should not have an observable effect on your code.