Share via


Zero Initialization of POD and Scalar Types

POD and scalar types will always be zero initialized if instantiated with the default constructor syntax.

struct S {
   void *operator new (unsigned int size, void*p, int i)
   {
      ((S*)p)->i = i; return p;
   }
     
   int i;
};

struct T
{
   int i;
   char c;
};

class C
{
   T t;
   int i;
public:
   C(): t(), i() {}   // Zero initializes members of class.
};

// Zero initialize members of t.
// t->i == 0 & t->c == 0
T* t = new T();

// Call placement new operator for S, then
// zero initialize members of pS.
// pS->i == 0 & pS->i != 10
S s;
S* pS = new( &s, 10 ) S();

// Zero initialize *pI
// *pI == 0
int* pI = new int();

// Zero initialize members of c
// c.t.i == 0 & c.t.c == 0 & c.i == 0
C c;

The Visual Studio .NET behavior ignores the () parentheses after the initialization and will always leave the members uninitialized. To revert to the Visual Studio .NET behavior for types initialized outside of a constructor's initialization list, remove the () parentheses as follows:

T* t = new T;   // Members contain uninitialized data.
S s;
S* pS = new( &s, 10 );   // pS->i == 10
int* pI = new int;   // *pI is uninitialized.

To revert to the Visual Studio .NET behavior for types initialized inside of a constructor's initialization list, remove initialization from the list as follows.

class C
{
   T t;
   int i;
public:
   C() {}   // Members of class are not initialized.
};

See Also

Reference

Breaking Changes in the Visual C++ Compiler