Sobes.tech
Junior — Middle

What is the purpose of smart pointers in programming?

sobes.tech AI

Answer from AI

Smart pointers in C++ are designed for automatic management of the lifetime of dynamically allocated objects. They help prevent memory leaks and errors related to improper resource release by automatically calling the object's destructor when the last smart pointer to it is destroyed or reassigned.

Main types of smart pointers:

  • std::unique_ptr — owns the object exclusively, cannot be copied, only moved.
  • std::shared_ptr — shares ownership of the object among multiple pointers; the object is deleted when the last shared_ptr is destroyed.
  • std::weak_ptr — a weak reference to an object, does not affect its lifetime, used to prevent cyclic references.

Example of using std::unique_ptr:

#include <memory>
#include <iostream>

struct MyClass {
    MyClass() { std::cout << "Created\n"; }
    ~MyClass() { std::cout << "Destroyed\n"; }
};

int main() {
    std::unique_ptr<MyClass> ptr(new MyClass());
    // The object will be automatically deleted when it goes out of scope
}

Thus, smart pointers simplify memory management and improve code safety.