为什么不能在D中实现结构的默认构造函数? [英] Why can I not implement default constructors for structs in D?
问题描述
编写代码
struct S
{
this()//编译时错误
{
}
}
给我一个错误消息说
仅允许使用@disable且没有主体的结构的默认构造函数。
为什么?
这种情况之一比最初预期的要复杂得多。
D与C ++相比,重要且有用的功能之一是,每个单个类型(包括所有用户类型)都有一些初始的非垃圾值,可以在编译时对其进行评估。它用作 T.init
,并具有两个重要的用例:
-
模板约束可以使用T.init值来检查是否可以对给定类型执行某些操作(引用Kenji Hara的代码段):
template isSomething(T){
枚举isSomething = is(typeof({
// T t1; //如果T是嵌套结构或@disable this()
则不好// T t2 = void; auto x = t2; //如果T是不可更改类型
则不好T T = T.init; //避免默认构造检查
...使用t。 ..
}));
}
-
您的变量始终正确初始化,除非您明确使用
int i = void
语法。
鉴于此,出现了一个难题。我们应该保证T()和T.init是相同的(就像许多C ++程序员所期望的那样)还是允许默认构造轻松地破坏该保证。据我所知,尽管令人惊讶,但还是做出了第一种方法更安全的决定。
但是,讨论不断涌现,提出了各种改进建议(例如,允许CTFE-能够使用默认构造函数)。 这样的线程最近才出现。 / p>
Writing code like
struct S
{
this() // compile-time error
{
}
}
gives me an error message saying
default constructor for structs only allowed with @disable and no body.
Why??
This is one of cases much more tricky than one can initially expect.
One of important and useful features D has over C++ is that every single type (including all user types) has some initial non-garbage value that can be evaluated at compile-time. It is used as T.init
and has two important use cases:
Template constraints can use T.init value to check if certain operations can be done on given type (quoting Kenji Hara's snippet):
template isSomething(T) { enum isSomething = is(typeof({ //T t1; // not good if T is nested struct, or has @disable this() //T t2 = void; auto x = t2; // not good if T is non-mutable type T t = T.init; // avoid default construct check ...use t... })); }
Your variables are always initialized properly unless you explicitly use
int i = void
syntax. No garbage possible.
Given that, difficult question arises. Should we guarantee that T() and T.init are the same (as many programmers coming from C++ will expect) or allow default construction that may easily destroy that guarantee. As far as I know, decision was made that first approach is safer, despite being surprising.
However, discussions keep popping with various improvements proposed (for example, allowing CTFE-able default constructor). One such thread has appeared very recently.
这篇关于为什么不能在D中实现结构的默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!