mardi 21 avril 2015

Default, value and zero initialization mess

I am very confused about value- & default- & zero-initialization. and especially when they kick in for the different standards C++03 and C++11 (and C++14).

I am quoting and trying to extend a really good answer Value-/Default-/Zero- Init C++98 and C++03 here to make it more general as it would help a lot of users if somebody could help fill out the needed gaps to have a good overview about what happens when?

The full insight by examples in a nutshell:

Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.

  • In C++1998 there are 2 types of initialization: zero and default
  • In C++2003 a 3rd type of initialization, value initialization was added.
  • In C++2011/C++2014 only list-initialization was added and the rules for value-/default-/zero-initialization changed a bit.

Assume:

struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m

maybe some more examples for the initializar list stuff for C++14 and =default ctor (due to the transition from c++03 to c++11)

In a C++98 compiler, the following should occur:

  • new A - indeterminate value
  • new A() - zero-initialize
  • new B - default construct (B::m is uninitialized)
  • new B() - default construct (B::m is uninitialized)
  • new C - default construct (C::m is zero-initialized)
  • new C() - default construct (C::m is zero-initialized)

In a C++03 conformant compiler, things should work like so:

  • new A - indeterminate value
  • new A() - value-initialize A, which is zero-initialization since it's a POD.
  • new B - default-initializes (leaves B::m uninitialized)
  • new B() - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.
  • new C - default-initializes C, which calls the default ctor.
  • new C() - value-initializes C, which calls the default ctor.

In a C++11 conformant compiler, things should work like so:

??? (please help if I start here it will anyway go wrong)

In a C++14 conformant compiler, things should work like so:

??? (please help if I start here it will anyway go wrong)

Aucun commentaire:

Enregistrer un commentaire