15用d编程左值与右值
import std.stdio;
void main() {
int i;immutable(int) imm;
auto arr = [ 1 ];
auto aa = [ 10 : "ten" ];
writeln(i, // 变量
imm, // 不变变量
arr, // array
arr[0], // array element
aa[10]); //关联数组元素
//上面都是左值
enum message = "hello";//被当作右值,清单常量
writeln(42, // 常数
message, //
i + 1, // 临时值
calculate(i)); // 返回的临时值
}
int calculate(int i) {
return i * 2;
}
左值,右值.右值可以看作不要了的值.
右值缺点:无地址,无法为其分配新值,在d中,与c++不同,右值不能按引用传递给参数.需要auto ref.在c++中,就是&&完美转发.
为什么不允许右值按引用传递,是担心将这个引用会在右值不可用时,还在被使用.
而函数模板参数可接受左值/右值.
因而左值按引用,右值按复制传递.
这里的D就不如c++,c++右值可以移动.
D的所有参数默认都是复制,也是一种浪费.
void incrementByTen()(auto ref int value) {
//右值是复制的,不是原来的右值
value += 10;
}
void main() {
int a;
int b;
incrementByTen(a);//左值这里是引用
incrementByTen(a + b);//右值是复制过来的
}
//判断是`左值还是右值`.
void incrementByTen()(auto ref int value) {
static if (__traits(isRef, value)) {
// 'value' is passed by reference
} else {
// 'value' is copied
}
}
要理解右值,只要理解右值就是垃圾值就行了.
懒执行.
典型的&&,||,及?:.
合理的
if ((s.length >= 1) && (s[0] == 'A')) {
// ...
}
函数指针,闭包,区间,都是懒操作.
浙公网安备 33010602011771号