D中基于堆栈的对象实例化

ano*_*cow 6 stack d allocation raii phobos

我正在学习D,并且因为我得到的错误而感到困惑.

考虑以下:

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()
Run Code Online (Sandbox Code Playgroud)

产量非常可观:

Hello, 32-bit world!
Elapsed time: 218 µs.
Run Code Online (Sandbox Code Playgroud)

现在考虑当我尝试在堆栈上初始化PerformanceCounter而不是使用托管堆时会发生什么:

 //auto t = new PerformanceCounter;  //From managed heap
 PerformanceCounter t;               //On the stack
Run Code Online (Sandbox Code Playgroud)

产量:

--- killed by signal 10
Run Code Online (Sandbox Code Playgroud)

我很难过.有什么想法为什么这打破?(Mac OS X 10.6.4上的DMD 2.049).在此先感谢帮助n00b.

Tim*_*Čas 5

您似乎将C++类与D类混合在一起.

D类总是通过引用传递(不像C++类),并且PerformanceCounter t不在堆栈上分配类,只是指向它的指针.

这意味着t设置为null因为,它是null指针的默认初始值设定项 - 因此是错误.

编辑:您可以将D Foo类视为C++ Foo*.

如果你想在堆上分配它,你可以尝试使用结构 - 它们也可以有方法,就像类一样.但是,他们没有继承权.

  • 如果您了解C#或Java,那么将D类实例视为与C#和Javas相同可能更有用. (2认同)