Junior — Middle
How are automatic memory management mechanisms implemented in C++, and what are smart pointers?
sobes.tech AI
Answer from AI
In C++, automatic memory management is implemented using smart pointers — special wrapper classes over regular pointers that automatically manage the lifetime of objects and memory deallocation.
Main types of smart pointers:
std::unique_ptr— owns the object exclusively, does not allow copying, automatically deletes the object when it goes out of scope.std::shared_ptr— implements reference counting, the object is deleted when the lastshared_ptrstops referencing it.std::weak_ptr— a weak reference to an object, does not affect its lifetime, used to prevent cyclic dependencies.
Example of using std::unique_ptr:
#include <memory>
#include <iostream>
int main() {
std::unique_ptr<int> ptr = std::make_unique<int>(42);
std::cout << *ptr << std::endl; // outputs 42
// memory will be freed automatically when exiting main
}
Thus, smart pointers help avoid memory leaks and errors with double deletion, simplifying resource management.