编译器错误 C3899

“var”:initonly 数据成员的左值不允许直接在类“class”的某个并行区域中使用

不能在位于并行区域的构造函数的该部分内初始化 initonly (C++/CLI) 数据成员。 这是因为编译器会执行该代码的内部重定位,因此它实际上不再是构造函数的一部分。

若要解析,请在构造函数中初始化 initonly 数据成员,但在并行区域之外。

示例

下面的示例生成 C3899。

// C3899.cpp
// compile with: /clr /openmp
#include <omp.h>

public ref struct R {
   initonly int x;
   R() {
      x = omp_get_thread_num() + 1000;   // OK
      #pragma omp parallel num_threads(5)
      {
         // cannot assign to 'x' here
         x = omp_get_thread_num() + 1000;   // C3899
         System::Console::WriteLine("thread {0}", omp_get_thread_num());
      }
      x = omp_get_thread_num() + 1000;   // OK
   }
};

int main() {
   R^ r = gcnew R;
   System::Console::WriteLine(r->x);
}