mardi 3 septembre 2019

thread_local x(2) doesn't call constructor

thread_local is defined in C++11 to have dynamic initialization semantics, so that it is permissible to declare non-POD types as thread local. However, in this program, I get an unexpected result:

#include <iostream>
struct A {
  A() : repr_(0) {}
  A(int) : repr_(2) {}
  int repr_;
};
thread_local A x(2);
int main() {
  std::cerr << x.repr_ << "\n";
  return 0;
}

On GCC 4.8 I get:

$ g++ --version
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-36)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ g++ -std=c++11 test.cpp && ./a.out
0

The program works correctly if I replace the thread_local line with:

thread_local A x = A(2);

What's going on here?

Aucun commentaire:

Enregistrer un commentaire