开发者

Confusion in understanding C++ standards

In C++98

12.6.2/4 : After the call to a constructor for class X has completed, if a member of X is neither specified in the constructor's mem-initializers, nor default-initialized, nor initialized during execution of the body of the constructor, the member has indeterminate value.

What does nor initialized during execution of the body 开发者_运维知识库of the constructor mean? Can a member be initialized inside the body of the constructor?


nor initialized during execution of the body of the constructor is not correct IMHO.

The wordings have been changed in C++03 from nor initialized (in C++98) to nor given a value

After the call to a constructor for class X has completed, if a member of X is neither specified in the constructor’s mem-initializers, nor default-initialized, nor value-initialized, nor given a value during execution of the body of the constructor, the member has indeterminate value.


It's actually very simple. class/struct members can include objects with default constructors, but if they don't, and you don't bother to give them a value in the initialiser list, nor set them within the body of the constructor, then basically the memory that they occupy - whatever was scrounged for them from the stack or heap - will still have old garbage in there, i.e. an indeterminate value.

Consider:

struct X
{
    X() : x1(1) { x2 = 2; }
    double x1, x2, x3;
    std::string x4;
};

Here, x1 and x2 are explicitly initialised by X's constructor, and x4 - being a std::string - is default constructed to be "" / length 0. x3, however, could be anything - and shouldn't be read from until after it's been set (it's undefined behaviour and really could bite on some systems - consider that the bit pattern of the memory it occupies may not even be a valid value for a double, so reading from it might trigger some CPU exception/trap/interrupt).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜