C++ 中是否有一个智能指针,当其目标被销毁时会自动清空?

发布于 2024-07-21 06:40:13 字数 112 浏览 2 评论 0原文

我找到了QPointer。 还有其他人吗?

I've found QPointer. Are there any others?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小姐丶请自重 2024-07-28 06:40:13

Boost - weak_ptr如果您也使用 shared_ptr,那么它有一些很好的功能,可以安全使用。 您保留对由 shared_ptr 生命周期管理的实例的 weak_ptr 引用。 当您需要使用底层实例时,请使用 shared_ptr 类的构造函数或 lock 方法将其转换为 shared_ptr 实例。 如果底层实例被删除,操作将会失败。 使用与 shared_ptr 类相同的方式是线程安全的:

shared_ptr<int> p(new int(5));
weak_ptr<int> q(p);

// some time later

if(shared_ptr<int> r = q.lock())
{
    // use *r
}

Boost - the weak_ptr has some nice features that make it safe to use, if you are also using shared_ptr. You keep a weak_ptr reference to an instance that is managed by shared_ptr lifetime. When you need to use the underlying instance, convert it to a shared_ptr instance using the constructor of the shared_ptr class, or the lock method. The operation will fail if the underlying instance was deleted. The use is thread safe in the same fashion as the shared_ptr class:

shared_ptr<int> p(new int(5));
weak_ptr<int> q(p);

// some time later

if(shared_ptr<int> r = q.lock())
{
    // use *r
}
表情可笑 2024-07-28 06:40:13

“boost::weak_ptr”与“boost::shared_ptr”配合得非常好(tr1 中也可用)

"boost::weak_ptr" works really well with "boost::shared_ptr" (also available in tr1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文