mercredi 20 juillet 2016

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. 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 ?

Aucun commentaire:

Enregistrer un commentaire