On Sunday, October 23, 2016 06:13:29 lumpyzhu via Digitalmars-d wrote: > thanks.. > but structs are copy by value, > In C++, I can use reference to avoid value-copy, > > ------------------------------------------ > class MyClass {....}; > void myFunc(const MyClass& a, MyClass& b) {...}; > > { > MyClass object; > myFunc(object); > // f will destroyed here. > } > ------------------------------------------ > in c++, I know where the object is destroyed.. > but how to convert this c++ code to d?
You can mark a parameter as ref, and you get something similar to C++'s &, except that it only works on parameters, return types, and the variable for the current element in a foreach loop (you can't declare local variables that are ref), and ref parameters only ever accept lvalues, even if they're const. e.g. void foo(ref int i) {...} ref int bar() { return _i; } foreach(i, ref e; arr) {...} I think that most D code just passes structs around without worrying about the cost of copying unless the struct is particularly large or profiling has shown that copying it is too expensive. For a lot of stuff, it simply isn't a problem. And when it is, there's ref, or the struct can be put on the heap and passed around by pointer. But because we don't have an equivalent for const& that accepts rvalues, using ref simply to avoid copying can get annoying. So, it doesn't make much sense to do it unless it's actually necessary (whereas a lot of C++ code does it just in case it matters). There is talk of possibly adding a way to pass rvalues by ref in D, in which case, you would get something similar to C++ const&, but there are problems caused by C++'s approach that we don't want in D, and D's const is enough more restrictive than C++ const that whatever we do can't be tied to const. - Jonathan M Davis