在 D 中,我可以直接在声明中初始化并期望初始化表达式是构造函数的一部分吗? 我来自 C#,情况就是这样。但是使用 DMD 2.071.0 我得到了其他行为。
class Other { }
class Test { Other nonStaticMember = new Other; }
void test()
{
auto t1 = new Test;
auto t2 = new Test;
// Assert is failing, the two Test instances are
// being initialized to the same reference
// instead of execute the Other constructor twice.
assert(t1.nonStaticMember !is t2.nonStaticMember);
}
如果这是有意为之的行为,则应在此处记录:https://dlang.org/spec/class.html对吧?
最佳答案
此代码在 D 中的作用与在 C# 中的作用不同。
在您的示例中,Other
在编译期间 被实例化。
即Other
在编译期间实例化一次,并放置在程序的数据段中。然后,对于所有 Test
实例,nonStaticMember
的初始值将默认指向 Other
的那个实例。
因此,一切都完全按照设计工作,即使来自其他语言时可能会令人惊讶。
If this is the intented behavior it should be documented here: https://dlang.org/spec/class.html right?
也许吧,但请注意,这种行为根本不是特定于类的。指向堆上分配的任何值的指针,作为全局或局部静态变量的初始值,将表现相同。每当编译期间需要表达式的值时(包括全局/静态变量的初始值设定项),D 都会尝试在编译时对其求值。几年前,这已经扩展到在“堆”上分配值,然后在程序的初始数据段中结束。
关于class - 初始化表达式是 D 中构造函数的一部分吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37631685/