lundi 25 novembre 2019

Is this an old C++ style constructor?

Here a piece of C++ code.

In this example, many code blocks look like constructor calls. Unfortunately, block code #3 is not (You can check it using https://godbolt.org/z/q3rsxn and https://cppinsights.io).

I think, it is an old C++ notation and it could explain the introduction of the new C++11 construction notation using {} (cf #4).

Do you have an explanation for T(i) meaning, so close to a constructor notation, but definitely so different?

struct T {
   T() { }
   T(int i) { }
};

int main() {
  int i = 42;
  {  // #1
     T t(i);     // new T named t using int ctor
  }
  {  // #2
     T t = T(i); // new T named t using int ctor
  }
  {  // #3
     T(i);       // new T named i using default ctor
  }
  {  // #4
     T{i};       // new T using int ctor (unamed result)
  }
  {  // #5
     T(2);       // new T using int ctor (unamed result)
  }
}

NB: thus, T(i) (#3) is equivalent to T i = T();

Aucun commentaire:

Enregistrer un commentaire