Search code examples
d

Segfault when using templated classes


Today I was evaluating D and I experimented a little bit with the language and I immediately run into a segfault.

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;
}

Why does this code segfault?


Solution

  • In D, classes are by default reference types and initialized to null. So your variable 'f' is null by default, and even were 'f' not null, Foo!(Bar).i is by default null as well.

    You would need to initialize them with 'auto f = new Foo!(Bar)()' and initialize 'i = new T()' in the constructor of Foo.

    Structs on the other hand are by default value types and do have a non-null default initializer.