Question

As in title. This question probably already has an answer but I failed to find one.

Was it helpful?

Solution

The fundamental conceptual difference between a naked pointer and a weak_ptr is that if the object pointed to is destroyed, the naked pointer won't tell you about it. This is called a dangling pointer: a pointer to an object that doesn't exist. They're generally hard to track down.

The weak_ptr will. In order to use a weak_ptr, you must first convert it into a shared_ptr. And if that shared_ptr doesn't point to anything, then the object was deleted.

For example:

#include <iostream>
#include <memory>

std::weak_ptr<int> wp;

void test()
{
    auto spt = wp.lock(); // Has to be copied into a shared_ptr before usage
    if (spt) {
        std::cout << *spt << "\n";
    } else {
        std::cout << "wp is expired\n";
    }
}

int main()
{
    {
        auto sp = std::make_shared<int>(42);
        wp = sp;
        test();
    }
    test();
}

Output

42
wp is expired

OTHER TIPS

A raw pointer is (at least normally) simply an address. You can't tell anything about what it points at from the pointer itself.

A weak_ptr is always associated with a shared_ptr, so we probably need to start with a shared_ptr to make any sense of a weak_ptr.

A shared_ptr is reference counted, so it keeps track of how many references (pointers) to an object exist, and automatically destroys the object when no more references to that object exist.

As I already said, a weak_ptr is associated with a shared_ptr. Unlike a shared_ptr, the existence of a weak_ptr does not increment the reference count for the pointee object. To use a weak_ptr, you must first convert it to a shared_ptr. If the current reference count is positive, that will succeed, and converting the weak_ptr to a shared_ptr will increment the reference count to signify that the converted pointer is a "real" reference to the object. If, on the other hand, the reference count is already zero (meaning the pointee object has already been destroyed) the attempt to convert the weak_ptr to a shared_ptr will simply fail.

A shared_ptr means shared ownership of the pointee object. The pointee object will remain in existence as long as at least one shared_ptr to that object exists, but as soon as the last shared_ptr to the object is destroyed, so will the pointee object.

A weak_ptr means non-owning access to the pointee object. It allows access if the object exists. If the object has been destroyed, it tells you that the pointee object no longer exists rather than attempting to access the destroyed object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top