Junior — Middle
What are the types of smart pointers in C++?
sobes.tech AI
Answer from AI
In C++, there are several main types of smart pointers that help manage object lifetimes and prevent memory leaks:
-
std::unique_ptr— provides exclusive ownership of an object. The object is destroyed when theunique_ptrgoes out of scope. It cannot be copied, but can be moved. -
std::shared_ptr— implements reference counting. Multiple pointers can own the same object, which is destroyed when the lastshared_ptris deleted. -
std::weak_ptr— a weak reference to an object managed byshared_ptr. It does not affect the object's lifetime and is used to prevent cyclic references.
Example usage:
#include <memory>
#include <iostream>
int main() {
std::unique_ptr<int> p1 = std::make_unique<int>(42);
// std::unique_ptr<int> p2 = p1; // Copy error
std::unique_ptr<int> p2 = std::move(p1); // Move ownership
std::shared_ptr<int> sp1 = std::make_shared<int>(100);
std::shared_ptr<int> sp2 = sp1; // Reference count increases
std::weak_ptr<int> wp = sp1; // Does not increase reference count
std::cout << *sp2 << std::endl; // 100
}