Junior — Middle
Can you explain what smart pointers are in C++ and how they work?
sobes.tech AI
Answer from AI
Smart pointers in C++ are special wrapper classes that manage the lifetime of dynamically allocated objects, automatically freeing memory when the object is no longer needed. They help prevent memory leaks and errors related to improper pointer management.
Main types of smart pointers:
std::unique_ptr— owns the object exclusively, cannot be copied, only moved. Frees memory upon destruction.std::shared_ptr— shares ownership of the object among multiple pointers. The object is deleted when the lastshared_ptris destroyed.std::weak_ptr— a weak reference to an object managed byshared_ptr, does not affect the reference count, 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 automatically freed when leaving scope
}