How to use shared_ptr to create multiple pointers to an object and auto deleted the object when out of scope in C++

1 Answer

0 votes
#include <iostream>
#include <memory>

class Example {
public:
    Example() {
         std::cout << "Example()" << "\n";
    }
     
    ~Example() {
         std::cout << "~Example()" << "\n";
    }
};

int main() {
    {
        std::shared_ptr<Example> ex1;
        {
            std::shared_ptr<Example> ex2 = std::make_shared<Example>();
            ex1 = ex2;
        }
    }
}
   
   
   
   
/*
run:
   
Example()
~Example()
   
*/

 



answered Feb 4, 2023 by avibootz

Related questions

...