Junior — Middle
Explain what a weak_ptr smart pointer is and how it differs from shared_ptr in C++.
sobes.tech AI
Answer from AI
weak_ptr and shared_ptr are smart pointers in C++ that manage the lifetime of objects.
- shared_ptr owns the object and maintains a reference count. The object is deleted when the last
shared_ptrto it is destroyed. - weak_ptr does not own the object and does not increase the reference count. It is used to observe an object managed by
shared_ptrwithout prolonging its lifetime.
Main difference:
weak_ptrhelps avoid cyclic references, which can lead to memory leaks, as it does not affect the reference count.- To access the object from a
weak_ptr, you need to call thelock()method, which returns ashared_ptrif the object still exists, or an emptyshared_ptrif it has been deleted.
Example:
std::shared_ptr<int> sp = std::make_shared<int>(10);
std::weak_ptr<int> wp = sp; // wp does not increase the count
if (auto spt = wp.lock()) { // try to get shared_ptr
std::cout << *spt << std::endl; // safely use the object
} else {
std::cout << "Object has already been deleted" << std::endl;
}