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. 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++ 4.9.2 gives following error (See live demo here )
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 )
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:
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; from [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.