为什么我不能返回nullptr std :: weak_ptr?

时间:2014-03-28 18:36:44

标签: c++ c++11 shared-ptr

所以我有一些代码:

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;

但这无法编译:

  

没有已知的从'std :: nullptr_t'到'const的参数1的转换   的std ::的weak_ptr&安培;'

为什么呢?我的approch是否允许其他对象持有另一个错误所拥有的东西?对于我来说,这似乎是weak_ptr的有效用例。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:7)

weak_ptr没有任何带有nullptr_t或原始指针的constructors,因此您无法构建一个nullptr作为参数。获取一个空的weak_ptr只是默认构造一个。

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 {};
}