Question

Is there a way to define a non-dynamic constructor which restricts the range of whichever default constructor lets me do

struct foo {
  int *bar;
};
static __thread foo myfoo[10] = {nullptr};

?

i.e., I want to do

class baz {
  public:
    baz() = default;
    constexpr baz(decltype(nullptr)) : qux(nullptr) { }

  private:
    int *qux;
};
static __thread baz mybaz[10] = {nullptr};

and have it work.

Currently, icpc tells me

main.cpp(9): error: thread-local variable cannot be dynamically initialized
  static __thread baz mybaz[10] = {nullptr};
                      ^
Was it helpful?

Solution

This:

static __thread baz mybaz[10] = {nullptr};

is equivalent to:

static __thread baz mybaz[10] = {baz(nullptr), baz(), baz(), baz(), baz(), ..., baz()};

Because this is general rule that implicit initialization of an array element is by default constructor.

So either do this:

static __thread baz mybaz[10] = {nullptr, nullptr, nullptr, ..., nullptr};

Or make your default constructor also constexpr...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top