在D中做"const指向非const"的正确方法?

Den*_*kiy 4 d

好吧,根据http://dlang.org/const-faq.html#head-const,没有办法在D中有一个指向非const的const指针.但是有一个很好的做法:在类中声明一个字段如果您忘记初始化它,const和编译器会通知您.有没有办法保护自己不要忘记D中一个类的init指针字段?

Ada*_*ppe 8

是:

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;
}
Run Code Online (Sandbox Code Playgroud)