0

What's the difference between these two statements?

C *c1 = new C;
C *c2 = new C();

The situation is explained here (Michael Burr's answer):

  • new C - default-initializes C, which calls the default ctor.
  • new C() - value-initializes C, which calls the default ctor.

I don't understand the difference. What do the terms "default-initializes" and "value-initializes" mean? Can you give examples?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Daros911
  • 435
  • 5
  • 14
  • Ok, but what's the difference between _default-initializes_ and _value-initializes_ as Michael aswerd in the source question? – Daros911 Dec 26 '20 at 15:44
  • 1
    @Daros911 if `C` is a class/struct type, both syntaxes call its default constructor. But if `C` is a fundamental type, like `int`, then `new int` will leave the value of the `int` unspecified, but `new int()` will initialize the value of the `int` to 0. That is the difference – Remy Lebeau Dec 26 '20 at 22:48
  • @RemyLebeau It'll also be uninitialized if the class/struct has a trivial constructor. – Aykhan Hagverdili Dec 27 '20 at 09:46

1 Answers1

1

The difference is when you use objects that are "Trivially Constructible", which means types that don't really have a constructor and neither do its members/base classes (including built-in types like int, double). Let's have a look at an example:

struct Foo
{
    int val1;
    int val2;
};

Here Foo does not have a constructor. When we create an object of type Foo, we can leave its members initialized with indeterminate values. Here's how we do it:

Foo* pf = new Foo;

Here pf->val1 and pf->val2 essentially have some garbage values.
We can also zero-initialize that object like so:

Foo* pf = new Foo();

Here pf->val1 and pf->val2 are initialized with zero. If they had a different type, like a pointer, they would have a different value, like null-pointer.

If the object does have a default constructor, the two examples do exactly the same thing.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93