Sobes.tech
Junior — Middle

Explain the concept of smart pointers and their purpose in memory management.

sobes.tech AI

Answer from AI

Smart pointers are objects that automatically manage the lifetime of dynamically allocated memory, preventing memory leaks and access errors.

Main types of smart pointers in C++:

  • std::unique_ptr — owns the object exclusively, does not allow copying, only moving. Releases memory upon destruction.
  • 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 managed by shared_ptr, does not affect the lifetime, used to prevent cyclic references.

Example of using unique_ptr:

#include <memory>

std::unique_ptr<int> ptr = std::make_unique<int>(42);
// ptr will automatically free memory when it goes out of scope

Thus, smart pointers simplify memory management and make code safer.