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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With