Sobes.tech
Junior — Middle

What is the purpose of the smart pointer weak_ptr in C++ and how does it differ from shared_ptr?

sobes.tech AI

Answer from AI

weak_ptr in C++ is used to hold a weak reference to an object managed by shared_ptr, without increasing the reference count. This helps to avoid cyclic dependencies that can lead to memory leaks.

Main differences:

  • shared_ptr owns the object and increases the reference count, ensuring the object remains alive as long as at least one shared_ptr exists.
  • weak_ptr does not own the object and does not affect the reference count. It allows checking if the object still exists and obtaining a shared_ptr if the object is still alive.

Example:

#include <iostream>
#include <memory>

int main() {
    std::shared_ptr<int> sp = std::make_shared<int>(42);
    std::weak_ptr<int> wp = sp; // does not increase the count

    if (auto spt = wp.lock()) { // try to get a shared_ptr
        std::cout << "Object exists: " << *spt << std::endl;
    } else {
        std::cout << "Object has been deleted" << std::endl;
    }

    sp.reset(); // object is deleted as shared_ptr is gone

    if (wp.expired()) {
        std::cout << "Object no longer exists" << std::endl;
    }
}