为什么内联声明不是不完整的类型? [英] Why an inline declaration is not an incomplete type?

查看:108
本文介绍了为什么内联声明不是不完整的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

struct Foo {
    struct Bar;
    Foo()
    {
        Bar bar; // Why isn't Bar an incomplete type?!
    }
    struct Bar {}; // Full definition
};

// struct Bar {}; // fails to compile due to incomplete type

int main()
{
    Foo foo;
}

它至少可以在2个编译器(gcc5.2,clang3.5)下编译良好.我的问题是:

It compiles fine under at least 2 compilers (gcc5.2, clang3.5). My question is:

  • 为什么在构造函数Foo::Foo中不认为Bar是不完整的类型,因为我在构造函数上方进行了前向声明,但在构造函数内部充分使用了它?
  • Why isn't Bar considered an incomplete type in the constructor Foo::Foo, as I forward-declare it above the constructor but fully use it inside the constructor?

每当我将Foo::Bar移到班级之外,换句话说Bar成为独立的班级,我就会得到预期的

Whenever I move Foo::Bar outside the class, in other words Bar becomes a stand-alone class, I get the expected

错误:聚集的'Foo :: Bar bar'类型不完整,无法定义

error: aggregate 'Foo::Bar bar' has incomplete type and cannot be defined

推荐答案

在成员规范中,该类被认为是功能体内完整的类,摘自C ++标准草案9.2 [class.mem] :

Within the member specification the class is considered complete within function bodies, from the draft C++ standard section 9.2 [class.mem]:

一个类被认为是完全定义的对象类型(3.9)(或 完整类型)在class-specifier的结尾}处. 在 类成员的规范,该类被认为是完整的 函数体,默认参数,使用声明介绍 继承构造函数(12.9),异常规范和 非静态数据成员(包括 嵌套类中的此类内容).否则被认为是不完整的 在自己的类成员规范内

A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, using-declarations introducing inheriting constructors (12.9), exception-specifications, and brace-or-equal-initializers for non-static data members (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification

这意味着您甚至不必转发声明Bar( 实时查看 ):

Which means you don't even have to forward declare Bar (see it live):

struct Foo {
    Foo()
    {
        Bar bar; 
    }
    struct Bar {};  
};

前瞻性声明对于避免违反 3.3.7第2和第3 节可能很有用.

Forward declaring could be useful in avoiding violation of section 3.3.7 paragraph 2 and 3.

这篇关于为什么内联声明不是不完整的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆