在 D 中做 "const pointer to non-const" 的正确方法?

Right way to do "const pointer to non-const" in D?

好的,根据 http://dlang.org/const-faq.html#head-const 在 D 中没有办法有一个指向非常量的 const 指针。但是有一个好的做法:在 class const 和编译器中声明一个字段如果您忘记初始化它,请告诉您。有什么方法可以防止自己忘记初始化 D 中 class 的指针字段?

是:

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;
}