我最近发现要更换:
std::shared_ptr<NEWT>(static_cast<NEWT>(old_ptr.get()));
Run Code Online (Sandbox Code Playgroud)
和
std::static_pointer_cast<NEWT>(odl_ptr);
Run Code Online (Sandbox Code Playgroud)
我知道如果不小心,前一种解决方案可能会导致重复删除。
我想知道引用计数是否使用后一种解决方案进行更新,以及如何实现?
使用static_pointer_cast或dynamic_pointer_cast使生成的shared_ptr能够进行正确的引用计数,而不会导致重复删除。这是通过为生成的强制转换指针调用特殊构造函数来实现的,下面是一个示例实现:
template< class T, class U >
std::shared_ptr<T> static_pointer_cast( const std::shared_ptr<U>& r ) noexcept
{
auto p = static_cast<typename std::shared_ptr<T>::element_type*>(r.get());
return std::shared_ptr<T>(r, p);
}
Run Code Online (Sandbox Code Playgroud)
请注意,调用的构造函数是
std::shared_ptr<T>(r,p);
Run Code Online (Sandbox Code Playgroud)
实际上是这样的形式
template< class Y >
shared_ptr( const shared_ptr<Y>& r, T *ptr );
Run Code Online (Sandbox Code Playgroud)
后者是一个别名构造函数,意味着该对象由r管理,而构造的shared_ptr是非托管的。要在没有 static_cast_pointer 的情况下具有相同的行为,必须编写
std::shared_ptr<T>(r, static_cast<T>(odl_ptr.get());
Run Code Online (Sandbox Code Playgroud)
其中您的 old_ptr 是其他类型。
这里的一些代码