Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero initialization of POD

struct Line
{
    Bounds          bounds_;
    Vector          origin_;
    uint32_t        begin_; 
    uint32_t        end_;   
    dist            ascent_;
    dist            descent_;
};

which is used as follows:

Line line = {};
while (!parser.done()) {
    line = Line(); // zero-initialize
    ...
}

Bounds and Vector are non-POD classes, dist is a typedef for int64_t.

However, an optimized 32-bit release build of VC++11, seems to leave at least parts of line uninitialized inside the while loop. Why? According to Do the parentheses after the type name make a difference with new?, it should have zero-initialized it, right?

I log the values of the struct members to a file:

  • after Line line = {};: non-POD types are default-initialized, the others are 0.
  • after line = Line();: POD types still default initialized, others contain random values.
like image 317
Daniel Gehriger Avatar asked Jan 09 '13 10:01

Daniel Gehriger


1 Answers

You may have found a compiler bug, although I seem to remember that in C++98 the requirements for initialising POD-structs were not as clearly described.

According to C++03, the expression Line() must result in a value-initialised Line object, which in this case means that all members must be zero-initialised (as all members are scalars).

Note that eventual padding between the members does not have to be set to any definite value, so that can cause a false-positive when you look at the Line object as a blob of memory.

The work-around is to provide a default constructor for Line that explicitly initialises all members.

like image 56
Bart van Ingen Schenau Avatar answered Sep 22 '22 22:09

Bart van Ingen Schenau