Search code examples
c++c++11destructorshared-ptrweak-ptr

Why destructor isn't invoked?


#include <memory>
#include <iostream>


struct Foo {
    Foo() { std::cout << "Constructor ...\n"; }
    void doSth() {std::cout << "hi" << std::endl;}
    ~Foo() { std::cout << "Destructor ...\n"; }
};


int main() {


   {std::weak_ptr<Foo> jack = (*(new std::shared_ptr<Foo>(new Foo)));

    std::cout << (jack).use_count() << std::endl;
    // std::shared_ptr<Foo> ptr = jack.lock();
    // std::cout << ptr.use_count() << std::endl;
  }
}

The use_count() return value is 1, therefore I think the last remaining shared_ptr owning the object will be destroyed and the destructor will therefore be invoked. But it isn't the case. Can any guy explain why? If I want to maintain the structure like this: new std::shared_ptr(new Foo) and also have the destructor invoked, what should I do? The code is just written for fun, without any application background.


Solution

  • Bizarrely, you dynamically allocated the shared_ptr, and never did anything to destroy it. If the shared_ptr isn't destroyed, neither will be the thing it points to.

    It's really not clear what you're trying to do here. You're writing strange, awkward code with no use case and wondering how to "make it work". Well to "make it work", write not-strange and non-awkward code. By definition that is the solution.