Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

d

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?

like image 771
Denis Gladkiy Avatar asked Feb 11 '23 02:02

Denis Gladkiy


1 Answers

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;
}
like image 63
Adam D. Ruppe Avatar answered Feb 19 '23 23:02

Adam D. Ruppe