mardi 5 mai 2020

Why instantiating a shared_ptr calling destructor?

Can someone explain why is the destructor of class bar being called in the line where the object of the same type is being initialized?

    #include <memory>
    #include <iostream>

    using namespace std;

    class bar
    {
      public:
        bar() {}

        ~bar() { std::cout << "destructor called " << std::endl; }
    };

    class foo
    {
      public:
        foo(std::shared_ptr<bar> barP) {}
    };


    int main() {

        std::shared_ptr<foo> f;
        std::cout << "before init " << std::endl;
        f = std::shared_ptr<foo>(new foo(std::shared_ptr<bar>(new bar())));
        std::cout << "after init"  << std::endl;
    }

Output:

before init 
destructor called 
after init

Aucun commentaire:

Enregistrer un commentaire