gpt4 book ai didi

c++ - std::shared_ptr 为 null 但不为空

转载 作者:行者123 更新时间:2023-12-04 01:09:41 27 4
gpt4 key购买 nike

比较:std::shared_ptr which is empty but not null

std::shared_ptr<T>别名构造函数让我们玩有趣的游戏。上面的 SO 帖子讨论了第一个参数是 std::shared_ptr<void>{nullptr} 的情况。 .我对反过来感兴趣。这是否保证即使 shared_ptr 也能使指向的对象保持事件状态? "is"nullptr (如果我们不保留对它的引用,将完全无法访问)?:

std::shared_ptr<S> ps = std::make_shared<S>();
auto& s = *ps; // Keep a reference to the S.
auto p = std::shared_ptr<S>(ps, nullptr); // Aliasing c'tor with null pointer.
ps = nullptr;
assert(ps == nullptr);
assert(p == nullptr);
foo(s); //< Is the S still alive here?

https://godbolt.org/z/M19s54

最佳答案

是的,“null but not empty”shared_ptr将使对象保持事件状态,因为它与 shared_ptr 共享所有权它是从 build 的。全部shared_ptr彼此共享所有权的 s 对存储在控制 block 中的原子引用计数有贡献,只有当此引用计数为零时,拥有的对象才会被销毁。

对于标准语,请参阅 [util.smartptr.shared.const]/14:

template<class Y> shared_ptr(const shared_ptr<Y>& r, element_type* p) noexcept;
Constructs a shared_ptr instance that stores p and shares ownership with r

没有对 p 的值指定约束;因此,它可以是任何有效的指针值,包括 null 甚至是尾后指针(尽管我不确定您为什么要这样做)。

然后查看 [util.smartptr.shared.dest]/(1.1):

If *this is empty or shares ownership with another shared_ptr instance (use_count() > 1), there are no side effects.

换句话说,当ps被销毁,它仍然与 p 共享所有权, 所以对象还没有被销毁。

生成的对象在通常意义上并不是真正不可访问的,因为仍然有可能销毁它。您无法用它做任何其他事情。

关于c++ - std::shared_ptr 为 null 但不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65258668/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com