Junior — Middle
Have you used std::weak_ptr in your projects to manage object lifetimes?
sobes.tech AI
Answer from AI
Yes, the std::weak_ptr is used for managing object lifetime together with std::shared_ptr to avoid cyclic references that can lead to memory leaks.
std::weak_ptr does not own the object but observes it. It allows checking whether the object still exists before accessing it, using the lock() method, which returns a std::shared_ptr if the object is still alive.
Example usage:
#include <iostream>
#include <memory>
struct Node {
std::shared_ptr<Node> next;
std::weak_ptr<Node> prev; // weak_ptr to prevent cycle
};
int main() {
auto first = std::make_shared<Node>();
auto second = std::make_shared<Node>();
first->next = second;
second->prev = first; // weak_ptr does not increase reference count
if (auto prevPtr = second->prev.lock()) {
std::cout << "Previous node is alive" << std::endl;
} else {
std::cout << "Previous node is expired" << std::endl;
}
}
Thus, std::weak_ptr helps safely manage object lifetime and prevent memory issues.