Search code examples
c++c++11shared-ptr

Why can't I return a nullptr std::weak_ptr?


So I have some code:

class Thing
{
public:
    Thing() = default;
};

class DbOfThings
{
public:
    DbOfThings() = default;

    std::weak_ptr<Thing> GetEntry(int someKey) const
    {
        // returns a weak_ptr from mThings, or null if a Thing
        // that has someKey was not found
        return std::weak_ptr<Thing>(nullptr);
    }
private
    // Idea is that this object owns these things, but other objects can grab a thing from here - but the thing can be killed off at any time
    std::vector<std::share_ptr<Thing>> mThings;

But this fails to compile with:

no known conversion for argument 1 from 'std::nullptr_t' to 'const std::weak_ptr&'

Why? Is my approch for letting other objects hold onto something that is owned by another wrong? This seems like a valid use case for weak_ptr to me. How can I make this work?


Solution

  • weak_ptr doesn't have any constructors that take a nullptr_t or raw pointers, so you cannot construct one with nullptr as an argument. To obtain an empty weak_ptr just default construct one.

    std::weak_ptr<Thing> GetEntry(int someKey) const
    {
        // returns a weak_ptr from mThings, or null if a Thing
        // that has someKey was not found
        return std::weak_ptr<Thing>();
        // or
        // return {};
    }