[英]constructor delegates to itself in g++ & clang++
Consider following program. 考虑以下程序。 I accidentally made a mistake in it. 我不小心弄错了。
struct T {
int s;
T() : T() {
s=9;
}
};
int main() {
T t;
}
The above code compiles & runs fine in some versions of g++ like g++ 4.8.1 (See live demo here ) & clang++ 3.6.0 (see live demo here ) & in MSVC++ 2015 but crashes at runtime. 上面的代码在某些版本的g ++中编译和运行,如g ++ 4.8.1(请参阅此处的实时演示)&clang ++ 3.6.0(请参阅此处的实时演示)和MSVC ++ 2015,但在运行时崩溃。 It gives me segmentation fault error. 它给了我分段错误错误。 I think it is due to recursion I mean recursively call the constructor. 我认为这是由于递归我的意思是递归调用构造函数。 But most recent versions of g++ & clang++ fails to compile this code by giving following error: 但是最新版本的g ++&clang ++无法通过提供以下错误来编译此代码:
g++ 4.9.2 gives following error (See live demo here ) g ++ 4.9.2给出以下错误(请参阅此处的实时演示)
prog.cc: In constructor 'T::T()':
prog.cc:3:10: error: constructor delegates to itself
T() : T() {
clang++ gives following error (See live demo here ) clang ++给出以下错误(请参阅此处的在线演示)
main.cpp:4:8: error: constructor for 'T' creates a delegation cycle [-Wdelegating-ctor-cycles]
T() : T() {
^
1 error generated.
So, the question here is which compiler is right here according to standard ? 那么,这里的问题是根据标准,哪个编译器就在这里? Is it bug in one of these compilers ? 这是其中一个编译器的错误吗? What exactly is happening here in above program? 上面的程序究竟发生了什么? Correct me If I am wrong somewhere in my understanding. 纠正我如果我在理解的某个地方错了。 Why same program exhibits different behaviour in different versions of these compilers ? 为什么同一程序在这些编译器的不同版本中表现出不同的行为?
From C++11, [class.base.init]¶6: 从C ++ 11开始,[class.base.init]¶6:
If a constructor delegates to itself directly or indirectly, the program is ill-formed; 如果构造函数直接或间接地委托给自己,程序就是格式错误; no diagnostic is required. 无需诊断。
All compilers are right – the code is broken, and the compiler isn't required to tell you so. 所有编译器都是正确的 - 代码被破坏了,编译器不需要告诉你。 At this point you have UB; 此时你有UB; from [intro.compliance]¶2: 来自[intro.compliance]¶2:
If a program contains a violation of a rule for which no diagnostic is required, this International Standard places no requirement on implementations with respect to that program. 如果程序包含违反不需要诊断的规则,则本国际标准不要求对该程序的实施。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.