为什么我对此有些困惑:
std::shared_ptr可以为空,而std::shared_ptr可以指向null,这两个概念不相同。
空的shared_ptr可以存储非null值,而存储null的shared_ptr可以具有正引用计数。
我现在想知道的是,如何在std::dynamic_pointer_cast之后正确测试强制转换是否成功? docs https://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast状态:

3-4) dynamic_cast<Y*>(r.get()) (If the result of the dynamic_cast is a null pointer value, the returned shared_ptr will be empty.)
但是由于不能保证为空的shared_ptr存储空值,因此我不确定动态转换是否成功进行正确定义的测试是什么

最佳答案

我真的不是很确定,但是可以这样:
在(23.11.2.2.9 shared_ptr casts)中声明The c++17 and c++20 standard draftsshared_ptr<T> dynamic_pointer_cast(const shared_ptr<U>& r) noexcept;返回值:
(5.1)—当dynamic_cast<typename shared_ptr<T>::element_type*>(r.get())返回非零时
pshared_ptr<T>(r, p)否则,为shared_ptr<T>()
在(20.11.3.11构造函数)中定义的shared_ptr<T>的默认构造函数
具有事后条件use_count() == 0 && get() == nullptr我将其读取为:如果原始指针类型转换返回nullptr,则智能指针类型转换将保存nullptr
因此,如果生成的共享指针不包含空指针(如果成功,它可能还包含空指针,但到目前为止,与我的应用程序无关),则我认为dynamic_pointer_cast成功。
但是我必须说,这是我对c++标准的第一次尝试,而且我也不理解,即使我也读过,失败的动态转换如何能够保存非空的空指针。

关于c++ - 如果我std::dynamic_pointer_cast并且基础dynamic_cast的结果为null,返回的shared_ptr是否保证在其中存储null?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62875515/

10-15 06:54