gpt4 book ai didi

c++ - boost::scoped_ptr 文档不一致?

转载 作者:搜寻专家 更新时间:2023-10-31 00:02:31 26 4
gpt4 key购买 nike

boost::scoped_ptr documentation包含一个称为 Handle/Body Idiom 的技术示例。它是用以下文字描述的:

The scoped_ptr_example_test.cpp sample program includes a header file, scoped_ptr_example.hpp, which uses a scoped_ptr<> to an incomplete type to hide the implementation.

然而,与此同时,在documentation for checked_delete据称:

A particularly troublesome case is when a smart pointer's destructor, such as boost::scoped_ptr::~scoped_ptr, is instantiated with an incomplete type. This can often lead to silent, hard to track failures. The supplied function and class templates can be used to prevent these problems, as they require a complete type, and cause a compilation error otherwise.

scoped_ptr 在其实现中确实使用了 checked_delete。在我看来,这两段经文似乎相互矛盾。此外,我未能编译我的代码,该代码试图使用以下消息来使用建议的技巧:

checked_delete.hpp:32: error: invalid application of 'sizeof' to 
incomplete type 'MyClass'

确实,scoped_ptr 的文档是错误的,还是我错过了什么?

最佳答案

他们并不矛盾。因为scoped_ptr是一个模板,由于代码中没有显式实例化,所以每个方法都是按需实例化。这意味着类型必须在 ~scoped_ptr<> 之前完成。被实例化,在这种情况下,它在保留类型完成后位于 .cpp 文件中(查找接近文件末尾的 example::~example(){},这是 ~scoped_ptr<> 被实例化的地方)

对于用户定义的析构函数,这实际上是一个有趣的用例,它看起来与编译器生成的析构函数完全相同,但允许您控制析构的何处/何时碰巧用一些智能指针启用了 PIMPL 模式。如果未声明和定义析构函数,则编译器会在需要的地方隐式定义析构函数,类型不完整,导致UB。

关于c++ - boost::scoped_ptr 文档不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7887652/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com