10

What is the difference between following two lines ?

int *a = new int;

int *a = new int();
talonmies
  • 70,661
  • 34
  • 192
  • 269
chom
  • 265
  • 1
  • 5
  • 16

2 Answers2

14
int *a = new int;

a is pointing to default-initialized object (which is uninitialized object in this case i.e the value is indeterminate as per the Standard).

int *a = new int();

a is pointing to value-initialized object (which is zero-initialized object in this case i.e the value is zero as per the Standard).

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 4
    C++11 § 8.5,p7, C++11 § 8.5,p5, and C++11 § 8.5,p6 for value-initializing, zero-initializing, and default-initializing, respectively, in case the OP is interested (and I highly doubt it). – WhozCraig Oct 06 '13 at 21:18
  • 4
    Note that testing may not expose this difference: unlike for automatic storage, dynamically allocated memory will often end up as zero in simple test programs, and only contain "garbage" in larger programs when earlier memory gets reused. –  Oct 06 '13 at 21:20
6

The first variant default-initializes the dynamically allocated int, which for built-in types such as int does not perform any initialization.

The second variant value-initializes it, which for int means zero-initialization, giving it value 0.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480