为什么我们不能使用这样的东西
struct
{
int bar;
} Foo;
int main() {}
在 C++ 模式下的 Comeau 编译器中,而在 C 模式下我们可以吗?
"ComeauTest.c", line 4: error: use of a type with no linkage to declare a variable with linkage } Foo; ^
最佳答案
每 3.5:8,
A type without linkage shall not be used as the type of a variable or function with external linkage unless
— the entity has C language linkage (7.5), or
— the entity is declared within an unnamed namespace (7.3.1), or
— the entity is not odr-used (3.2) or is defined in the same translation unit.
请注意,这是从 C++98 开始放宽的,它具有(在 3.5:8 中):
A name with no linkage [...] shall not be used to declare an entity with linkage.
此规则的原因是,为了从另一个翻译单元引用该变量,您需要知道其类型,这对于未命名类型来说是不可能的。实际上,这是因为具有外部链接的变量与其类型损坏以生成明确的名称,这对于未命名类型来说是不可能的。
但是,在您的代码中,实体 Foo
(可以说)不是 odr 使用的,并且肯定是已定义的,因此它应该被符合标准的 C++11 编译器接受,Comeau 是不是。
关于c++ - Comeau 编译器中的未命名结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12355161/