6
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.
Jonas
  • 121,568
  • 97
  • 310
  • 388
Daniel Gehriger
  • 7,339
  • 2
  • 34
  • 55
  • How are you observing this? By running the program normally and having tests *in the code*, or by looking at it in the debugger? – R. Martinho Fernandes Jan 09 '13 at 10:36
  • @chris: It is value-initialization, which I think, in this case is equivalent to zero-initialization. – Nawaz Jan 09 '13 at 10:37
  • @R.MartinhoFernandes: by writing the values to a log file. When running under the debugger, the memory location used for the variables happens to be zeroed out, so it's not visible. – Daniel Gehriger Jan 09 '13 at 10:39
  • @Nawaz, Oh, I must be confused. For some reason, I thought `Line()` would default-initialize it and those that were initialized would be initialized in the assigned to one. – chris Jan 09 '13 at 10:39

1 Answers1

6

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.

Bart van Ingen Schenau
  • 15,488
  • 4
  • 32
  • 41
  • Yes, it really looks like a compiler bug. I'll update my question. – Daniel Gehriger Jan 09 '13 at 11:02
  • I've played around a bit with the code, and it looks like an optimizer bug of the 32-bit VC11 compiler. It simply forgets to zero-initialize the POD struct members. Compiling w/o optimization, or using the 64-bit compiler produces the assembly correct code. – Daniel Gehriger Jan 09 '13 at 12:24