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

H. S. Teoh hsteoh at qfbox.info
Thu Nov 3 15:40:02 UTC 2022


On Thu, Nov 03, 2022 at 04:41:14AM +0000, Siarhei Siamashka via Digitalmars-d-learn wrote:
[...]
> ```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
> }
> ```
[...]

D does not have the equivalent of C++'s allocating a class instance on
the stack.  In D, all class instances are allocated on the heap and
class variables are references to them.  Declaring an instance of A as a
local variable initializes it to the null reference, so invoking a
method on it rightly segfaults.


T

-- 
Freedom: (n.) Man's self-given right to be enslaved by his own depravity.


More information about the Digitalmars-d-learn mailing list