Placement new and uninitialized POD members

前端 未结 2 1686
眼角桃花
眼角桃花 2021-01-01 22:45

Does the C++ standard guarantee that uninitialized POD members retain their previous value after a placement new?

Or more precisely, will the following assert always

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-01 23:19

    C++11 12.6.2/8 "Initializing bases and members" says:

    In a non-delegating constructor, if a given non-static data member or base class is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer) and the entity is not a virtual base class of an abstract class (10.4), then

    • if the entity is a non-static data member that has a brace-or-equal-initializer, the entity is initialized as specified in 8.5;
    • otherwise, if the entity is a variant member (9.5), no initialization is performed;
    • otherwise, the entity is default-initialized (8.5).

    Default initialization on an int does nothing (8.5/6 "Initializers"):

    To default-initialize an object of type T means:

    • if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
    • if T is an array type, each element is default-initialized;
    • otherwise, no initialization is performed.

    So the member alpha should be left alone.

提交回复
热议问题