混合类和结构

2021-12-09 00:00:00 class struct c++ undefined-behavior

我很清楚class 和 struct 之间的区别,但是我很难权威地说这是否定义明确:

I'm well aware of the difference between class and struct, however I'm struggling to authoritatively say if this is well defined:

// declare foo (struct)
struct foo;

// define foo (class)
class foo {
};

// instance of foo, claiming to be a struct again! Well defined?
struct foo bar;

// mixing class and struct like this upsets at least one compiler (names are mangled differently)
const foo& test() {
   return bar;
}

int main() {
   test();
   return 0;
}

如果这是未定义的行为,有人可以指出我权威(即 ISO 中的章节和诗句)参考的方向吗?

If this is undefined behaviour can someone point me in the direction of an authoritative (i.e. chapter and verse from ISO) reference?

编译器在处理此问题时遇到问题(Carbide 2.7)相对较旧,我尝试过的所有其他编译器都对此非常满意,但显然这并不能证明任何事情.

The compiler with problems handling this (Carbide 2.7) is relatively old and all the other compilers I've tried it on are perfectly happy with this, but clearly that doesn't prove anything.

我的直觉是这应该是未定义的行为,但我找不到任何可以证实这一点的东西,我很惊讶 GCC 版本或 Comeau 已经警告过了.

My intuition was this ought to be undefined behaviour but I can't find anything to confirm this and I'm surprised that none of the GCC versions or Comeau so much as warned about it.

推荐答案

在我看来,它像是已定义的行为.特别是,§9.1/2 说:

It looks to me like it's defined behavior. In particular, §9.1/2 says:

仅由 class-key identifier ; 组成的声明要么是对当前作用域中的名称或标识符的前向声明作为类名.它将类名引入当前作用域.

A declaration consisting solely of class-key identifier ; is either a redeclaration of the name in the current scope or a forward declaration of the identifier as a class name. It introduces the class name into the current scope.

标准在定义一个类时区分使用classstructunion,但在这里,谈论关于声明,没有这样的区别――使用一个 class-key 等同于任何其他.

The standard distinguishes between using class, struct or union when defining a class, but here, talking about a declaration, no such distinction is made -- using one class-key is equivalent to any other.

相关文章