Junior — Middle
What types of smart pointers exist in C++ and how do they differ?
sobes.tech AI
Answer from AI
In C++, there are three main types of smart pointers from the standard library <memory>:
-
std::unique_ptr — owns the object exclusively. The object is destroyed when the unique_ptr goes out of scope. It cannot be copied, only moved.
-
std::shared_ptr — implements reference counting. Multiple shared_ptrs can own the same object. The object is destroyed when the last shared_ptr is destroyed or reset.
-
std::weak_ptr — does not own the object but only references it to avoid cyclic references with shared_ptr. It allows checking if the object exists before accessing it.
Example:
#include <memory>
#include <iostream>
int main() {
std::unique_ptr<int> uptr = std::make_unique<int>(10);
// std::unique_ptr<int> uptr2 = uptr; // Error: cannot copy
std::shared_ptr<int> sptr1 = std::make_shared<int>(20);
std::shared_ptr<int> sptr2 = sptr1; // Reference count increases
std::weak_ptr<int> wptr = sptr1; // Does not own the object
if (auto spt = wptr.lock()) { // Check if the object exists
std::cout << *spt << std::endl;
}
}