“正确的做法”;指向非常量的常量指针;在D区?
好的,根据这个例子,没有办法在D中有一个指向非常量的常量指针。但是有一个很好的实践:在一个类const中声明一个字段,如果您忘记初始化它,编译器会告诉您。有什么方法可以防止自己忘记在D中初始化类的指针字段吗?是:“正确的做法”;指向非常量的常量指针;在D区?,d,D,好的,根据这个例子,没有办法在D中有一个指向非常量的常量指针。但是有一个很好的实践:在一个类const中声明一个字段,如果您忘记初始化它,编译器会告诉您。有什么方法可以防止自己忘记在D中初始化类的指针字段吗?是: void main() { // ConstPointerToNonConst!(int) a; // ./b.d(4): Error: variable b.main.a default construction is disabled for type ConstP
void main() {
// ConstPointerToNonConst!(int) a; // ./b.d(4): Error: variable b.main.a default construction is disabled for type ConstPointerToNonConst!int
int b;
auto a = ConstPointerToNonConst!(int)(&b); // works, it is initialized
*a = 10;
assert(b == 10); // can still write to it like a normal poiinter
a = &b; // but can't rebind it; cannot implicitly convert expression (& b) of type int* to ConstPointerToNonConst!int
}
struct ConstPointerToNonConst(T) {
// get it with a property without a setter so it is read only
@property T* get() { return ptr; }
alias get this;
// disable default construction so the compiler forces initialization
@disable this();
// offer an easy way to initialize
this(T* ptr) {
this.ptr = ptr;
}
private T* ptr;
}
指针默认初始化为null,取消引用将导致SEGFULT(在大多数体系结构上)是的,但这是一个运行时错误。我想要一个更便宜(在开发时)处理的编译时错误。而且这些东西不在火卫一中?=)看起来不错。有没有关于这种模式的讨论或阅读?Rebindable就是这样工作的,我们之前也讨论过使用这个基本思想的NotNull,但是要让它与继承一起正确工作有很多困难,所以对于标准库来说还不够好。但是,虽然它对于一般用途的stdlib还不够好,但它可能对您来说已经足够好了!此外,我认为知道如何自己实现它是有用的,因为这样你就可以选择你想要它如何工作。正如您所看到的,代码并不多,但有很多选择。