Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我可以从boost';什么是弱ptr?_C++_Boost_Shared Ptr_Smart Pointers_Weak References - Fatal编程技术网

C++ 我可以从boost';什么是弱ptr?

C++ 我可以从boost';什么是弱ptr?,c++,boost,shared-ptr,smart-pointers,weak-references,C++,Boost,Shared Ptr,Smart Pointers,Weak References,是否可以从boost::weak_ptr获取原始指针?Boost的shared_ptr有get()方法和“->”运算符。弱ptr不具有相同功能的背后是否有一些基本原理?A弱ptr持有非所有权引用,因此它引用的对象可能不再存在。使用由弱\u ptr持有的原始指针本身就是危险的 正确的方法是使用弱ptr::lock()将弱ptr提升为共享ptr,并从中获取指针 解释了为什么作为弱\u ptr的一部分提供get()功能是不安全的,并提供了可能导致问题的代码示例。在获取原始指针之前,首先需要从弱\u p

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

A
弱ptr
持有非所有权引用,因此它引用的对象可能不再存在。使用由
弱\u ptr
持有的原始指针本身就是危险的

正确的方法是使用
弱ptr::lock()
弱ptr
提升为
共享ptr
,并从中获取指针


解释了为什么作为
弱\u ptr
的一部分提供
get()
功能是不安全的,并提供了可能导致问题的代码示例。

在获取原始指针之前,首先需要从弱\u ptr派生共享的\u ptr

您可以调用以获取共享\u ptr或共享\u ptr构造函数:

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

int* raw = boost::shared_ptr<int>(example).get();
boost::弱ptr示例;
...
int*raw=boost::shared_ptr(示例).get();

这是一个老问题,公认的答案是好的,所以我不太愿意再发布另一个答案,但似乎缺少一个好的惯用用法示例:

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
}
boost::弱\u ptr弱\u示例;
...
if(boost::shared_ptr example=weak_example.lock())
{
//使用example做一些事情;使用example.get()获取
//原始指针,*仅当*仅在此范围内使用,而不是缓存。
}
其他的
{
//如果对象已被破坏,则执行一些合理的操作(通常不执行任何操作)
}

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

,这是不安全的-当临时
共享的\u ptr
被销毁时,如果对象被删除,可能会留下一个悬空的指针。只要您使用原始指针,您就应该一直保持
共享的\u ptr
。因此,如果您得到一个
共享的\u ptr
的原始指针,并且该指针随后也会被销毁,那么您可能会留下一个悬空的指针。。。在使用多线程的情况下,如果(!weak.expired())weak->run(),则在运行代码
时甚至可以留下一个悬空指针由于指向的对象可能会在测试和方法执行之间被销毁(我假设方法本身是正确同步的)…@Matthieu:当然可以,就像如果显式地
删除
对象但保留指向该对象的指针,则会留下一个悬空指针一样。必须将
弱\u ptr
提升为
共享\u ptr
的要点是,它鼓励您按照通常用于
共享\u ptr::get
的规则,正确确定原始指针的使用范围。对于直接从
弱\u ptr
获取的原始指针,没有等效的方法可以正确地确定其使用范围。