gpt4 book ai didi

c++ - 锁()的实现

转载 作者:太空狗 更新时间:2023-10-29 21:13:10 28 4
gpt4 key购买 nike

根据 boost :

To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock.

同样,来自 boost:

shared_ptr<T> lock() const;

//Returns: expired()? shared_ptr<T>(): shared_ptr<T>(*this).

据我了解,返回shared_ptr<T>(*this)意味着创建一个引用计数为 1 的新 shared_ptr;而这绝对不是我们想要的。所以可能我没有理解正确。有人会解释吗?谢谢!

最佳答案

不,这实际上是 shared_ptr 的要点 - 复制的实例将指向相同的底层数据并增加两个实例的引用计数。

这意味着shared_ptr<T>(*this)将创建一个额外的 shared_ptr指向相同数据的实例并将增加两者的引用计数 this和新实例。


实际代码中其实更复杂,如原文shared_ptr通过 weak_ptr 访问数据实例,但实际上是原始的 shared_ptr数据在最后共享(共享引用计数在特定 shared_ptr 对象的所有现有拷贝中增加)。

关于c++ - 锁()的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45328184/

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