shared_ptr和unique_ptr的类型不完整
我想了解为什么 unique_ptr
析构函数要求类型在销毁时完整,而 shared_ptr
则不是这样。 Howard Hinnant 的这篇博客 简要提到它与静态删除器和动态删除器有关。我正在寻找更详细的解释,解释为什么会出现这种情况(可能是编译器实现特定的,在这种情况下,示例会有所帮助)。使用动态删除器,它是否限制析构函数被内联?
I would like to understand why unique_ptr
destructors require the type to be complete upon destruction while that isn't the case with shared_ptr
. This blog from Howard Hinnant briefly mentions it has to do with static vs. dynamic deleters. I'm looking for a more detailed explanation of why that might be the case (it may be compiler implementation specific in which case an example would be helpful). With dynamic deleters, does it restrict the destructor from being inlined?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
霍华德·欣南特(Howard Hinnant)正在简化。他的确切意思是,如果您使用 std::unique_ptr 的默认删除器,则需要一个完整的类型。对于默认删除器,它只是为您调用
delete
。静态和动态删除器的要点是
只要
dynamic_delete
指向一个在A
也被定义的地方定义的函数,你就拥有了明确定义的行为。为了防止未定义的行为,默认删除器检查完整类型,可以将其实现为
Howard Hinnant was simplifying. What he precisely meant was if you use the default deleter for
std::unique_ptr
, you need a complete type. For the default deleter, it simply callsdelete
for you.The gist of static and dynamic deleters is
As long as
dynamic_delete
points to a function that's defined whereA
is also defined, you have well-defined behaviour.To prevent undefined behaviour, the default deleter checks for a complete type, which may be implemented as
如此简单,我相信这很简单该默认的驱动器需要了解数据成员的大小。对于
unique_ptr
,eleter是对象表示的一部分您使用I believe that is as simple as that default destructor needs to know the size of data members. For
unique_ptr
the deleter is part of the object representation, whilst forshared_ptr
the actual deleter is not that relevant, because it's stored in the control block, no matter what kind of deleter you use