lundi 5 septembre 2016

Is it guaranteed that constructor is called exactly when the variable is defined?

Consider the following code:

#include <cstdio>

struct A {
  A() {
    printf("Bar\n");
  }
};

int main() {
  printf("Foo\n");
  A a;
  return 0;
}

Is it guaranteed that it will print Foo\nBar\n, in that order? My experience says "yes", but I want to have some quote from C++11 standard or MSDN reference to point to, because somebody told me that it's possible for compiler to call constructor before the actual line of declaration.

It would be more obvious if the constructor had some arguments (because they can depend on values which are not computed when function starts), and less obvious if there was default constructor only. Say, JavaScript is famous for making variables defined before the var line available:

function main() {
  console.log(x);
  var x = 2;
  console.log(y);
}
main();

The code above will print undefined as value of x and then fail with y is not defined.

Aucun commentaire:

Enregistrer un commentaire