example1_basic.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <memory>

class MyClass {
public:
    MyClass() { std::cout << "MyClass Constructor" << std::endl; }
    ~MyClass() { std::cout << "MyClass Destructor" << std::endl; }
    void sayHello() const { std::cout << "Hello from MyClass" << std::endl; }
};

int main() {
    std::unique_ptr<MyClass> ptr = std::make_unique<MyClass>();
    ptr->sayHello();  // Access the object using the unique_ptr

    // Memory leak when return is executed. The class destructor is not called
    MyClass* myclass = new MyClass();  // also call destructor when out of scope. So why unique_ptr?

    // No need to manually delete the object, it will be destroyed automatically
    return 0;
}
Back to std_unique_ptr