Junior
What smart pointers exist in C++?
sobes.tech AI
Answer from AI
std::unique_ptr, std::shared_ptr, std::weak_ptr.
-
std::unique_ptr:- Exclusive ownership of an object.
- Cannot be copied, but can be moved (
std::move). - Automatically deletes the object when it goes out of scope or is destroyed.
- Lightweight, with no overhead for reference counting.
#include <memory> // Creating a unique_ptr std::unique_ptr<int> up1(new int(10)); // Moving ownership std::unique_ptr<int> up2 = std::move(up1); // up1 is now nullptr // up2 owns the object -
std::shared_ptr:- Shared ownership of an object.
- Uses a reference counter to track the number of
shared_ptrs pointing to the resource. - The object is deleted when the last
shared_ptrpointing to it is destroyed. - Supports copying and moving.
- Has overhead for reference counting (usually allocated separately).
- Can create cyclic references, leading to memory leaks.
#include <memory> // Creating a shared_ptr std::shared_ptr<int> sp1 = std::make_shared<int>(20); // Copying ownership std::shared_ptr<int> sp2 = sp1; // Reference count increases // sp1 and sp2 share ownership of the object -
std::weak_ptr:- Does not own the object.
- Represents a "weak" reference to an object managed by one or more
shared_ptrs. - Used to prevent cyclic references between
shared_ptrs. - Does not increase the reference count.
- To safely access the object, convert it to a
shared_ptrusinglock(). If the object has been deleted,lock()returns an emptyshared_ptr.
#include <memory> // Creating a shared_ptr std::shared_ptr<int> sp = std::make_shared<int>(30); // Creating a weak_ptr from shared_ptr std::weak_ptr<int> wp = sp; // Checking and using the object if (auto shared_from_weak = wp.lock()) { // Access the object via shared_from_weak } else { // The object has been deleted }