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

时间:2015-01-25 13:56:03

标签: d

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

中忘记一个类的init指针字段

1 个答案:

答案 0 :(得分: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;
}