问题
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