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

Tejas notrealemail at gmail.com
Thu Nov 3 17:46:02 UTC 2022


On Thursday, 3 November 2022 at 15:40:02 UTC, H. S. Teoh wrote:
> 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

I think his main problem will go away if the code just refuses to 
compile, since it's known at compile time that one is trying to 
dereference a `null` pointer

Check my post, `A& a;` refuses to compile in C++20 atleast, 
asking to be explicitly initialized, thus averting the problem 
altogether


More information about the Digitalmars-d-learn mailing list