Junior — Middle
Explain the working principle of the shared_ptr smart pointer in C++ and its advantages.
sobes.tech AI
Answer from AI
shared_ptr is a smart pointer in C++ that implements reference counting for a dynamically allocated object. It keeps track of the number of active owners of the object and automatically deletes the object when the last shared_ptr pointing to it is destroyed or reassigned.
Advantages:
- Automatic management of the object's lifetime, preventing memory leaks.
- Allows multiple parts of a program to share ownership of the object.
- Safe in exception scenarios, as memory is freed automatically.
Example usage:
#include <memory>
#include <iostream>
int main() {
std::shared_ptr<int> p1 = std::make_shared<int>(42);
{
std::shared_ptr<int> p2 = p1; // reference count increases
std::cout << *p2 << std::endl; // output: 42
} // p2 goes out of scope, reference count decreases
std::cout << *p1 << std::endl; // object still alive
} // p1 goes out of scope, object is deleted