使用模板化类时的Segfault

时间:2014-12-17 16:27:15

标签: d

今天我正在评估D,我用这种语言进行了一些实验,我立即遇到了一个段错误。

import std.stdio;
import std.typecons;
class Foo(T){
public:
  T i;
}
class Bar{
public:
  int hello = 0;
}

void main()
{
  Foo!(Bar) f;
  int i = f.i.hello;
}

为什么这段代码会出现错误?

1 个答案:

答案 0 :(得分:4)

在D中,类默认为引用类型并初始化为null。所以你的变量' f'默认为null,甚至是' f'非空,Foo!(Bar).i默认为null。

您需要使用' auto f = new Foo!(Bar)()'来初始化它们。并初始化' i = new T()'在Foo的构造函数中。

另一方面,结构是默认值类型,并且具有非null的默认初始值设定项。

相关问题