有没有一种方法可以定义一个非动态的构造函数,它会限制我可以执行的默认构造函数的范围

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




即,我想做

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

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


并使其起作用。

目前,icpc告诉我

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

最佳答案

这个:

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


等效于:

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


因为这是一般规则,所以默认情况下,数组元素的隐式初始化是构造函数。

因此,要么这样做:

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


或者让您的默认构造函数也可以constexpr ...

关于c++ - icpc在c++中使用非动态构造函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13336609/

10-13 08:05