Sobes.tech
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_ptr to 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_ptr without prolonging its lifetime.

Main difference:

  • weak_ptr helps 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 the lock() method, which returns a shared_ptr if the object still exists, or an empty shared_ptr if 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;
}