https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61343
Bug ID: 61343
Summary: [C++11] Missing default initialization for class with
default constructor
Product: gcc
Version: 4.10.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: tejohnson at google dot com
The following test case does not call the default constructor when expected:
/////////////////////////////
#include <iostream>
struct Foo {
int value;
Foo() noexcept {
std::cout << this << " constructed. Setting value to twelve.\n";
value = 12;
}
};
static thread_local Foo a{};
static thread_local Foo b;
static __attribute__((noinline)) void UseA() {
const int value = a.value;
std::cout << "Value of A: " << value << "\n";
}
static __attribute__((noinline)) void UseB() {
const int value = b.value;
std::cout << "Value of B: " << value << "\n";
}
int main(int argc, char** argv) {
// std::cout << "Address of A: " << &a << "\n";
// std::cout << "Address of B: " << &b << "\n";
UseA();
UseA();
UseB();
UseB();
UseA();
UseA();
return 0;
}
//////////////////////////
When compiled with the current trunk compiler it gives the output:
> Value of A: 0
> Value of A: 0
> 0x7f2bc9150728 constructed. Setting value to twelve.
> 0x7f2bc9150724 constructed. Setting value to twelve.
> Value of B: 12
> Value of B: 12
> Value of A: 12
> Value of A: 12
I would expect something like:
> 0x7ffa4bc63720 constructed. Setting value to twelve.
> 0x7ffa4bc63724 constructed. Setting value to twelve.
> Value of A: 12
> Value of A: 12
> Value of B: 12
> Value of B: 12
> Value of A: 12
> Value of A: 12
It appears as though the empty brace initialization for 'a', which should
result in the user-defined default constructor being invoked, does not actually
do so. Instead the object is zero-initialized until accessing 'b', which
finally causes the default constructor for 'a' to be run as well.
Google ref: b/15250505