Search code examples
stackdallocationraiiphobos

Stack-based object instantiation in D


I'm learning D, and am confused by an error I'm getting.

Consider the following:

module helloworld;

import std.stdio;
import std.perf;

ptrdiff_t main( string[] args )
{
     auto t = new PerformanceCounter;    //From managed heap
     //PerformanceCounter t;             //On the stack

     t.start();
     writeln( "Hello, ", size_t.sizeof * 8, "-bit world!" );
     t.stop();

     writeln( "Elapsed time: ", t.microseconds, " \xb5s." );

     return 0;
} //main()

Yields a perfectly respectable:

Hello, 32-bit world!
Elapsed time: 218 µs.

Now consider what happens when I attempt to initialize PerformanceCounter on the stack instead of using the managed heap:

 //auto t = new PerformanceCounter;  //From managed heap
 PerformanceCounter t;               //On the stack

Yields:

--- killed by signal 10

I'm stumped. Any thoughts as to why this breaks? (DMD 2.049 on Mac OS X 10.6.4). Thanks in advance for helping a n00b.


Solution

  • You seem to be mixing up C++ classes with D classes.

    D classes are always passed by reference (unlike, say, C++ classes), and PerformanceCounter t does not allocate the class on the stack, merely a pointer to it.

    This means that t is set to null because, well, null is the default initializer for pointers - hence the error.

    EDIT: You can think of D Foo class as a C++'s Foo*.

    If you want this to be allocated on the heap, you could try using structs instead - they can also have methods, just like classes. They do not, however, have inheritance.