Self reference in construction

  • A+
Category:Languages

I have just discovered that the following code compiles with both gcc 5.4 and the Intel compiler 18.0.2. Clang 6.0.0 just gives a warning.

#include <vector>  int main() {   std::vector<double> v = v;    return 0; } 

I had a bug in my code that was very similar and I am scared that those kind of code can compile. My question are:

  • Is it legal C++? If yes, what is it supposed to do?
  • How to catch those "bugs" at compile time?

Is it legal C++? If yes, what is it supposed to do?

It's a well-formed program, but it exhibits Undefined Behaviour, because it reads an uninitialised variable. This means there are no constraints on its behaviour (it can legally do literally anything).

How to catch those "bugs" at compile time?

Enable enough warnings and build with "treat warnings as errors." With enough warnings on, gcc 5.4 catches it correctly. Note that in the case of gcc, this also requires turning optimisation on, because gcc does some analyses (such as unused variables) only when optimising.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: