【问题标题】:Why can't I return a nullptr std::weak_ptr? [duplicate]为什么我不能返回 nullptr std::weak_ptr? [复制]
【发布时间】:2014-03-28 18:36:43
【问题描述】:

所以我有一些代码:

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;

但这无法编译:

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

为什么?我让其他物体抓住另一个错误拥有的东西的方法是错误的吗?对我来说,这似乎是 weak_ptr 的一个有效用例。我怎样才能做到这一点?

【问题讨论】:

  • 好像没有这样的构造函数,但是你可以使用默认的:return {};
  • 如果向量是唯一拥有对象的东西,为什么要使用shared_ptr 而不是unique_ptr? (或者你不能为unique_ptr拥有的对象创建weak_ptrs,即使弱指针不会导致指向的对象的所有权发生变化?)
  • ...哦,我明白了。因为shared_ptr 可以将weak_ptr 作为构造函数,所以允许指向唯一指针拥有的对象的弱指针将需要杀死唯一指针,尽管shared_ptr 有一个unique_ptr 构造函数,它只是间接地这样做可能会有奇怪的效果。
  • @jab 更根本的是,.lock() 是您访问weak_ptr 的方式,如果它不能延长指向对象的生命周期,那有什么好处?
  • 是的,奇怪的是unique_ptr 没有weak_ptr - 当你想传递它但不改变所有者时

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


【解决方案1】:

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

【讨论】:

  • 这种构造函数的唯一可能用途是采用空指针。任何其他指针都没有合理的语义。
  • 该死 - 我确定我在执行此操作时遇到了编译器错误,但是可以!
猜你喜欢
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
  • 2017-08-28
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多