8

What is the difference between the following 2 two initializations?

class Pod {
public:
    int a, b;
};

Pod *p1 = new Pod;
Pod *p2 = new Pod();
codefx
  • 9,872
  • 16
  • 53
  • 81

1 Answers1

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

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • 1
    Though the difference is essentially nonexistent in the case of `int`, in the first case the members are default initialized rather than uninitialized. – Jerry Coffin Mar 17 '13 at 02:22
  • @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* – David Rodríguez - dribeas Mar 17 '13 at 02:39
  • 1
    @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). – Jerry Coffin Mar 17 '13 at 02:57
  • @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 – David Rodríguez - dribeas Mar 17 '13 at 03:16
  • 1
    @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. – Jerry Coffin Mar 17 '13 at 03:43