Right way to do “const pointer to non-const” in D?

泪湿孤枕 提交于 2020-01-02 06:33:33

问题


Ok, according to http://dlang.org/const-faq.html#head-const there is no way to have a const pointer to non-const in D. But there is a good practice: declare a field in a class const and compiler let you know if you forget to initialize it. Is there any way to protect myself from forgetting to init pointer field of a class in D?


回答1:


Yes:

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


来源:https://stackoverflow.com/questions/28137190/right-way-to-do-const-pointer-to-non-const-in-d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!