Sobes.tech
Junior — Middle

Can you explain what smart pointers are and how they work in resource management?

sobes.tech AI

Answer from AI

Smart pointers in C++ are wrapper classes around regular pointers that automatically manage the lifetime of the object they point to, preventing memory leaks and double deletion errors.

Main types of smart pointers:

  • std::unique_ptr — owns the object exclusively, cannot be copied, only moved. When the smart pointer is destroyed, the object is automatically deleted.
  • std::shared_ptr — implements reference counting. Multiple pointers can own the same object, and 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 increase the reference count, used to prevent cyclic dependencies.

Example with unique_ptr:

#include <memory>
#include <iostream>

int main() {
    std::unique_ptr<int> p(new int(42));
    std::cout << *p << std::endl; // 42
    // The object will be automatically deleted when going out of scope
    return 0;
}

Thus, smart pointers help manage resources safely, freeing the programmer from manually calling delete.