What's the correct way of creating an instance of class in D?

Siarhei Siamashka siarhei.siamashka at gmail.com
Thu Nov 3 04:41:14 UTC 2022


C++ code:
```C++
#include <iostream>
class A {
public:
   void foo() { std::cout << "foo" << std::endl; }
};
int main() {
   auto a1 = new A;
   a1->foo(); // prints "foo"
   A a2;
   a2.foo();  // prints "foo"
   delete a1;
}
```
D code:
```D
@safe:
import std.stdio;
class A {
   void foo() { writeln("foo"); }
}
void main() {
   auto a1 = new A;
   a1.foo(); // prints "foo"
   A a2;
   a2.foo(); // Segmentation fault
}
```

I didn't expect to see a segmentation fault in the code, which is 
a straightforward conversion from C++. And especially not with 
the use of the `@safe` attribute. What's going on here?

```
$ ldc2 --version
LDC - the LLVM D compiler (1.30.0):
   based on DMD v2.100.1 and LLVM 14.0.6
   built with LDC - the LLVM D compiler (1.30.0)
   Default target: x86_64-pc-linux-gnu
```



More information about the Digitalmars-d-learn mailing list