做“指向非常量的常量指针”的正确方法在D? [英] Right way to do "const pointer to non-const" in D?
本文介绍了做“指向非常量的常量指针”的正确方法在D?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好,根据 http://dlang.org/const-faq.html# head-const 不能在D中具有指向非const的const指针。但是有一个好的实践:在const类中声明一个字段,如果您忘记初始化它,编译器会告诉您。有什么方法可以保护自己,避免忘记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?
推荐答案
是:
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;
}
这篇关于做“指向非常量的常量指针”的正确方法在D?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文