Junior — Middle
Can you explain the principle of smart pointers and how they manage memory?
sobes.tech AI
Answer from AI
Smart pointers are wrapper objects around regular pointers that automatically manage the lifetime of dynamically allocated memory, preventing leaks and double-free errors.
The main types of smart pointers in C++:
std::unique_ptr— owns the object exclusively, does not allow copying, only moving. When the smart pointer is destroyed, the memory is freed.std::shared_ptr— implements reference counting. Memory is freed when the lastshared_ptrpointing to the object is destroyed.std::weak_ptr— a weak reference to an object managed byshared_ptr, does not affect the object's lifetime, used to prevent cyclic references.
Example of using std::shared_ptr:
#include <memory>
#include <iostream>
struct Foo {
Foo() { std::cout << "Foo created\n"; }
~Foo() { std::cout << "Foo destroyed\n"; }
};
int main() {
std::shared_ptr<Foo> sp1 = std::make_shared<Foo>();
{
std::shared_ptr<Foo> sp2 = sp1; // increases the reference count
std::cout << "Inside block\n";
} // sp2 is destroyed, reference count decreases
std::cout << "Outside block\n";
} // sp1 is destroyed, the Foo object is deleted
Thus, smart pointers help manage memory safely without explicit calls to delete.