什么是`std::reinterpret_pointer_cast`,什么时候应该使用它?

dar*_*une 2 c++ casting c++17

参考链接: std::reinterpret_pointer_cast

是否应该在涉及weak_ptr或shared_ptr涉及时使用(为什么?总是?有时?)

wal*_*nut 8

像所有其他std::*_pointer_cast函数一样,这允许您在包装的不同指针类型之间进行转换std::shared_ptr,就像转换了相应的原始指针一样,但同时保留了共享所有权。

所以std::reinterpret_pointer_cast<T>(ptr)(大部分)与 相同std::shared_ptr<T>(reinterpret_cast<T*>(ptr.get())),重要的区别在于后者会导致强制转换原始指针存储在与原始指针无关的新共享指针中,因此托管对象将被双重删除一次由原始共享指针复数和一次由新的共享指针(后者可能具有错误的类型)。

取而代之的std::reinterpret_pointer_cast<T>(ptr)是(主要)等同于std::shared_ptr<T>(ptr, reinterpret_cast<T*>(ptr.get())),它采用所谓的混叠构造的std::shared_ptr。它允许获得std::shared_ptr引用任何指针(第二个参数),同时仍然拥有与原始shared_ptr(第一个参数)相关联的所有权。

所以你应该使用std::reinterpret_pointer_castif 你有一个std::shared_ptr,reinterpret_cast如果它是一个原始指针,你就会使用它。

由于 for 的用例reinterpret_cast很少,您将更有可能使用std::dynamic_pointer_castor std::static_pointer_cast,这对于类层次结构中的向下和侧向转换很有用。