我想了解为什么
unique_ptr
析构函数在销毁时需要类型完成,而shared_ptr
则不需要。Howard Hinnant的博客简要提到这与静态和动态删除器有关。我正在寻找更详细的解释,说明为什么会出现这种情况(如果是编译器特定实现,则示例将很有帮助)。对于动态删除器,是否限制了析构函数的内联?
shared_ptr
在构造时捕获了一个删除器,并将其存储在控制块中。例如,shared_ptr<Base> ptr(new Derived);
可以正常工作,并最终调用正确的析构函数~Derived
,即使Base
没有虚析构函数(因为构造函数本质上保存了[dervied_ptr]() { delete dervied_ptr; }
,而析构函数调用相同的内容)。std::unique_ptr<T>
不会执行类似的操作;它的析构函数只是对该unique_ptr
存储的类型为T*
的原始指针p
执行delete p
。 - Igor TandetnikpImpl
习惯时,使用shared_ptr
与unique_ptr
有什么影响。具体来说,为什么不需要在cpp
文件中定义包装类的析构函数,似乎与unique_ptr
的析构函数内联有关,而这在shared_ptr
中是不可能的,但我不明白其中的原因。 - user3882729unique_ptr<T>
needsT
to be a complete type at the point where~unique_ptr
destructor is called.shared_ptr<T>
needsT
(or rather, the pointer passed to the constructor, which may e.g. be a class derived fromT
) to be complete at the point where its constructor is called. If you don't put the destructor of the wrapper class into thecpp
file, it will be implicitly defined in theh
file, and that implicit definition is going to call the destructor of the smart pointer, at the timepImpl
class is incomplete. That's a problem forunique_ptr
, not a problem forshared_ptr
- Igor Tandetnik