繁体   English   中英

我可以从boost的weak_ptr获得一个原始指针吗?

[英]Can I get a raw pointer from boost's weak_ptr?

是否有可能从boost :: weak_ptr获取原始指针? Boost的shared_ptr有get()方法和“ - >”运算符。 weak_ptr背后是否有一些理由不具备相同的功能?

weak_ptr包含非拥有引用,因此它引用的对象可能不再存在。 使用weak_ptr持有的原始指针本身就很危险。

正确的方法是使用weak_ptr::lock()weak_ptr提升为shared_ptr并从中获取指针。

Boost weak_ptr文档解释了为什么提供get()功能作为weak_ptr一部分是不安全的,并且提供了可能导致问题的代码示例。

这是一个古老的问题,并且接受的答案是好的,所以我不愿发布另一个答案,但似乎缺少的一件事是一个很好的习惯用法示例:

boost::weak_ptr<T> weak_example;
...
if (boost::shared_ptr<T> example = weak_example.lock())
{
    // do something with example; it's safe to use example.get() to get the
    // raw pointer, *only if* it's only used within this scope, not cached.
}
else
{
    // do something sensible (often nothing) if the object's already destroyed
}

这个习惯用法的一个关键优势是强指针的作用域是if-true块,这有助于防止意外使用非初始化的引用,或者保持强引用的时间长于实际需要的时间。

首先需要在获取原始指针之前从weak_ptr派生shared_ptr。

您可以调用lock来获取shared_ptr或shared_ptr构造函数:

boost::weak_ptr<int> example;
...

int* raw = boost::shared_ptr<int>(example).get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM