【发布时间】:2011-06-19 11:32:55
【问题描述】:
我很清楚difference between class and struct,但是我很难权威地说这是否定义明确:
// 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 中的章节和诗句)参考的方向吗?
处理此问题的编译器 (Carbide 2.7) 相对较旧,我尝试过的所有其他编译器都对此非常满意,但显然这并不能证明什么。
我的直觉是这应该是未定义的行为,但我找不到任何东西来证实这一点,我很惊讶 GCC 版本或 Comeau 都没有警告过它。
【问题讨论】:
-
AFAIK,结构是一个具有公共成员的类;也许编译器会将结构前向声明“变形”为前向类声明。 (??)
-
@Max: 这样做是必须的还是只是为了好看?
-
@Matthieuh - 我不认为这是重复的,因为我问的是它是否是明确定义的行为,而不是一个(可能不符合标准的)编译器产生的警告意味着什么。跨度>
-
@peoro:我无法让 Clang 的在线演示发出警告,你有文字吗?
标签: c++ class struct undefined-behavior