Middle
What pointer is used with shared_ptr?
sobes.tech AI
Answer from AI
weak_ptr.
#include <memory>
#include <iostream>
int main() {
auto shared = std::make_shared<int>(10); // Create a shared_ptr
std::weak_ptr<int> weak = shared; // Create a weak_ptr from shared_ptr
if (auto locked = weak.lock()) { // Try to get a shared_ptr from weak_ptr
std::cout << "Value: " << *locked << std::endl;
} else {
std::cout << "Object is deleted." << std::endl;
}
shared.reset(); // The object pointed to by shared_ptr is deleted
if (auto locked = weak.lock()) { // Second attempt, object is already deleted
std::cout << "Value: " << *locked << std::endl;
} else {
std::cout << "Object is deleted." << std::endl;
}
return 0;
}
weak_ptr used together with shared_ptr helps solve the problem of cyclic references and prevents memory "hang" when two or more objects managed by shared_ptr refer to each other, and reference counters never reach zero.
Here are the main properties of weak_ptr:
- Does not increase the reference count:
weak_ptrholds a "weak" reference to the object managed byshared_ptr, without increasing its strong reference count. - Object life check: Using the
lock()method, you can attempt to obtain ashared_ptrfrom aweak_ptr. If the object is still alive,lock()returns a validshared_ptr; otherwise, an emptyshared_ptr. - No direct access:
weak_ptrdoes not provide direct access to the object's content via*or->operators. Access is only possible after a successful call tolock().
Using weak_ptr is a standard way to break reference cycles in data structures that use shared_ptr, such as graphs or doubly linked lists.