引用链接: std::reinterpret_pointer_cast
应该在 weak_ptr
时使用它或 shared_ptr
参与(为什么?总是?有时?)
最佳答案
像所有其他人一样 std::*_pointer_cast
函数,这允许您在包装在 std::shared_ptr
中的不同指针类型之间进行转换。好像相应的原始指针被强制转换,但同时保留了共享所有权。
所以std::reinterpret_pointer_cast<T>(ptr)
(大部分)与 std::shared_ptr<T>(reinterpret_cast<T*>(ptr.get()))
相同, 重要的区别是后者会导致 cast 的原始指针被存储在一个新的与原共享指针无关的共享指针中,这样被管理的对象会被原共享指针复合体双删除一次,由新的(后者可能具有错误的类型)。
而是 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_cast
如果您有 std::shared_ptr
你会使用 reinterpret_cast
如果它是一个原始指针。
由于 reinterpret_cast
的用例很少见,您将更有可能使用 std::dynamic_pointer_cast
或 std::static_pointer_cast
,这对于类层次结构中的向下和侧向转换很有用。
关于c++ - 什么是 `std::reinterpret_pointer_cast`,什么时候应该使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60635130/