9

What is the difference between the following 2 two initializations?

class Pod { public: int a, b; }; Pod *p1 = new Pod; Pod *p2 = new Pod(); 
6
  • As JamesMcLaughlin said, no difference, furthermore that's not limited to PODs. Commented Mar 17, 2013 at 2:16
  • @DavidRodríguez-dribeas How so? Commented Mar 17, 2013 at 2:17
  • @JamesMcLaughlin: Read section 8.5 in the standard :) Commented Mar 17, 2013 at 2:18
  • @DavidRodríguez-dribeas Yep, looks like I was wrong! Thanks. Commented Mar 17, 2013 at 2:21
  • 1
    This previous thread explains zero, default and value-initialized and has examples stackoverflow.com/questions/1613341/… Commented Mar 17, 2013 at 2:41

1 Answer 1

11

In the first case the object is left uninitialized, while in the second case the object is guaranteed to be value-initialized, which in this case as the type is POD it means zero-initialized

Sign up to request clarification or add additional context in comments.

5 Comments

Though the difference is essentially nonexistent in the case of int, in the first case the members are default initialized rather than uninitialized.
@JerryCoffin: Yes I should have been clearer, that part is also due to the fact that it is a POD, for which default-initialization means that the object is left uninitialized
@DavidRodríguez-dribeas: ...but in C++11, it's not restricted to POD types either (IIRC, it should apply to the somewhat broader category of all trivially copyable types).
@JerryCoffin: trivially copyable types? Not sure how that would matter here (there are no copies anywhere) and I cannot find a reference in n3777 that supports that. For value-initialization the distinction is between a class type with/without user provided default constructor. For default-initialization of a class type it implies calling the default constructor, which if defined implicitly will recursively cause default-initialization of the members... at the end members of fundamental types are left uninitialized
@DavidRodríguez-dribeas: Copying isn't really relevant, but being trivially copyable is a looser requirement than being POD, and you don't have to meet the extra requirements to be POD for default initialization to mean leaving uninitialized.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.