gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:19:25 25 4
gpt4 key购买 nike

我正在学习 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()

产生一个完全可敬的:
Hello, 32-bit world!
Elapsed time: 218 µs.

现在考虑当我尝试在堆栈上初始化 PerformanceCounter 而不是使用托管堆时会发生什么:
 //auto t = new PerformanceCounter;  //From managed heap
PerformanceCounter t; //On the stack

产量:
--- killed by signal 10

我难住了。关于为什么会中断的任何想法? (Mac OS X 10.6.4 上的 DMD 2.049)。
在此先感谢您帮助 n00b。

最佳答案

您似乎将 C++ 类与 D 类混为一谈。

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

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

编辑:你可以想到 D Foo作为 C++ 的类 Foo* .

如果您希望在堆上分配它,您可以尝试使用结构体 - 它们也可以有方法,就像类一样。然而,他们没有继承权。

关于D 中基于堆栈的对象实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4006309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com