shared_ptr和unique_ptr的类型不完整

发布于 2025-01-20 12:45:44 字数 281 浏览 2 评论 0原文

我想了解为什么 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

久光 2025-01-27 12:45:44

霍华德·欣南特(Howard Hinnant)正在简化。他的确切意思是,如果您使用 std::unique_ptr 的默认删除器,则需要一个完整的类型。对于默认删除器,它只是为您调用delete

静态和动态删除器的要点是

class A;

void static_delete(A* p)
{
    delete p;
}

void (*dynamic_delete)(A*) = /* somehow */;

int main()
{
    A* p = /* somehow */;
    static_delete(p);  // undefined behaviour
    dynamic_delete(p); // maybe not
}

只要 dynamic_delete 指向一个在 A 也被定义的地方定义的函数,你就拥有了明确定义的行为。

为了防止未定义的行为,默认删除器检查完整类型,可以将其实现为

void default_delete(A* p)
{
    static_assert(sizeof(A) > 0);
    delete p;
}

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 calls delete for you.

The gist of static and dynamic deleters is

class A;

void static_delete(A* p)
{
    delete p;
}

void (*dynamic_delete)(A*) = /* somehow */;

int main()
{
    A* p = /* somehow */;
    static_delete(p);  // undefined behaviour
    dynamic_delete(p); // maybe not
}

As long asdynamic_delete points to a function that's defined where A 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

void default_delete(A* p)
{
    static_assert(sizeof(A) > 0);
    delete p;
}
爱要勇敢去追 2025-01-27 12:45:44

我想理解为什么  code> unique_ptr   destructors要求在破坏时完成类型,而与  code> sharone_ptr

并非如此

如此简单,我相信这很简单该默认的驱动器需要了解数据成员的大小。对于unique_ptr,eleter是对象表示的一部分您使用

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

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 for shared_ptr the actual deleter is not that relevant, because it's stored in the control block, no matter what kind of deleter you use

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文