为什么 D 不允许在堆栈上创建对象?
Why D doesn't allow object creation on stack?
考虑以下程序(查看现场演示 here)
import std.stdio;
class myclass
{
public:
int get_a()
{
return a;
}
private:
int a=3;
}
int main()
{
myclass m; // It should be myclass m=new myclass();
writefln("%d",m.get_a());
return 0;
}
C++ 支持自动(堆栈分配)和动态(堆分配)对象。但是为什么每个 class 对象都必须在 D 中动态分配?为什么 D 不支持堆栈分配的对象?
另一个令人惊讶的事情是 ideone
给出编译器错误为:
prog.d(14): Error: null dereference in function _Dmain
但是当我在我的本地机器上使用 dmd2 编译器尝试它时,它给我的是运行时错误而不是编译时错误。为什么?为什么这个程序的行为不同?
以下是 dmd2 给出的我在本地机器上遇到的错误。
object.Error@(0): Access Violation
----------------
0x00402056
0x00405F9B
0x00405EB1
0x00403D93
0x7651EE6C in BaseThreadInitThunk
0x7758377B in RtlInitializeExceptionChain
0x7758374E in RtlInitializeExceptionChain
D 允许将 类 放入堆栈,参见 std.typecons.scoped
。
您在 ideone 上看到的 null 取消引用错误是因为编译器在优化期间发现了这个问题(ideone 似乎启用了优化)。尝试将 -O
开关添加到本地编译器调用。
考虑以下程序(查看现场演示 here)
import std.stdio;
class myclass
{
public:
int get_a()
{
return a;
}
private:
int a=3;
}
int main()
{
myclass m; // It should be myclass m=new myclass();
writefln("%d",m.get_a());
return 0;
}
C++ 支持自动(堆栈分配)和动态(堆分配)对象。但是为什么每个 class 对象都必须在 D 中动态分配?为什么 D 不支持堆栈分配的对象?
另一个令人惊讶的事情是 ideone
给出编译器错误为:
prog.d(14): Error: null dereference in function _Dmain
但是当我在我的本地机器上使用 dmd2 编译器尝试它时,它给我的是运行时错误而不是编译时错误。为什么?为什么这个程序的行为不同? 以下是 dmd2 给出的我在本地机器上遇到的错误。
object.Error@(0): Access Violation
----------------
0x00402056
0x00405F9B
0x00405EB1
0x00403D93
0x7651EE6C in BaseThreadInitThunk
0x7758377B in RtlInitializeExceptionChain
0x7758374E in RtlInitializeExceptionChain
D 允许将 类 放入堆栈,参见 std.typecons.scoped
。
您在 ideone 上看到的 null 取消引用错误是因为编译器在优化期间发现了这个问题(ideone 似乎启用了优化)。尝试将 -O
开关添加到本地编译器调用。