gpt4 book ai didi

c++ - 什么时候类型被认为是完整的?

转载 作者:可可西里 更新时间:2023-11-01 17:56:50 24 4
gpt4 key购买 nike

考虑以下代码片段。 boost::scoped_ptr 的析构函数在主函数结束时被调用。析构函数使用 boost::checked_delete 来释放封装的 Widget 指针。

#include <boost/scoped_ptr.hpp>
#include <iostream>

class Widget;
Widget *make_widget();

int main()
{
boost::scoped_ptr<Widget> sp(make_widget());
// std::cout << sizeof(Widget) << std::endl;
}

class Widget
{
public:
Widget() {}
~Widget() { std::cout << "Widget destructor called." << std::endl; }
};

Widget *make_widget()
{
return new Widget;
}

我预计此代码无法编译,因为类 Widget 在 scoped_ptr<Widget> 的析构函数点不完整被调用。然而,这可以在 g++ 4.8 和 Visual Studio 2010 上干净地编译。请注意带有 sizeof(Widget) 的注释语句main函数中的表达式。如果我取消注释,它将无法编译,这意味着 Widget那时一定是不完整的。

这种行为的正确解释是什么?

编辑:一些答案(现已删除)指向未定义的行为,但我希望在 scoped_ptr 中使用 checked_delete|的析构函数导致编译失败。 FWIW,我正在使用 Boost 1.55。

最佳答案

5.3.5 Delete [expr.delete]

5 If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined.

因此,您当然会期望它是 UB,因为 Widget::~Widget() 是非常重要的,并且您会期望 boost 中的安全防护会出错。

现在,让我们深入挖掘:

2.2 Phases of translation [lex.phases]

8 Translated translation units and instantiation units are combined as follows: [ Note: ... ] Each translated translation unit is examined to produce a list of required instantiations. [ Note: This may include instantiations which have been explicitly requested (14.7.2). —end note ] The definitions of the required templates are located. It is implementation-defined whether the source of the translation units containing these definitions is required to be available. [ Note: An implementation could encode sufficient information into the translated translation unit so as to ensure the source is not required here. —end note ] All the required instantiations are performed to produce instantiation units. [ Note: These are similar to translated translation units, but contain no references to uninstantiated templates and no template definitions. —end note ] The program is ill-formed if any instantiation fails.

你被翻译阶段拯救了:
翻译翻译单元,然后实例化模板...

关于c++ - 什么时候类型被认为是完整的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24841083/

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