Junior — Middle
What types of smart pointers exist in C++ and how do they differ in their behavior?
sobes.tech AI
Answer from AI
In C++, there are three main types of smart pointers that help manage object lifetime and prevent memory leaks:
-
std::unique_ptr — owns the object exclusively. The object is deleted when the unique_ptr goes out of scope. Cannot be copied, only moved.
-
std::shared_ptr — shares ownership of the object among multiple pointers. The object is deleted when the last shared_ptr owning it is destroyed.
-
std::weak_ptr — does not own the object but refers to it through a shared_ptr. Allows checking if the object exists without increasing the reference count.
Example:
#include <memory>
#include <iostream>
int main() {
std::unique_ptr<int> uptr = std::make_unique<int>(10);
// std::unique_ptr<int> uptr2 = uptr; // Error, copying is forbidden
std::shared_ptr<int> sptr1 = std::make_shared<int>(20);
std::shared_ptr<int> sptr2 = sptr1; // Both own the object
std::weak_ptr<int> wptr = sptr1; // Does not own, but can check existence
if (auto spt = wptr.lock()) { // Check if the object still exists
std::cout << *spt << std::endl;
}
}
Thus, the choice of smart pointer depends on the ownership requirements and object lifetime management.