What's the difference between raw pointer and weak_ptr?

NPS picture NPS · May 26, 2013 · Viewed 8.2k times · Source

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

Answer

Nicol Bolas picture Nicol Bolas · May 26, 2013

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