On Wednesday, March 14, 2012 01:43:54 Andrej Mitrovic wrote: > On 3/14/12, Jonathan M Davis <jmdavisp...@gmx.com> wrote: > > As I understand it, auto ref is supposed to work with _any_ function. The > > _compiler_ decides whether it's best to use a ref or a value. > > I never really understood the need for 'const ref' with structures. If > the compiler knows the size of a structure shouldn't it be able to > automatically figure out if it's faster to pass a struct by value or > by pointer? But maybe there's more to it than that?
In C++, the compiler _never_ decides that sort of thing. It always passes stuff the way that you tell it to. Before auto ref, D was exactly the same way. If you tell function's parameter is ref or const ref, then it takes it be reference, otherwise it takes it by value. That works great in C++, because const& in C++ will take rvalues, but D doesn't do that (if nothing else, because Andrei is completely against it on the grounds that it makes it so that a function can't determine whether it's dealing with an rvalue or an lvalue when given a const&; I don't understand why this is a problem - in fact I think that most people don't - but he's quite adamant about it, and he may very well be right). So, D ends up with ref and const ref, just like C++'s & and const& except that const& doesn't take rvalues, which is where all the pain starts. Ultimately, that resulted in the suggestion of auto ref, which _does_ allow the compiler to decide - unlike every other parameter type. So, the reasons for const ref really have nothing to do with auto ref, and I'd tend to argue that const ref is pretty pointless at this point. If you want the struct to be passed by value, then don't use auto ref or ref. If you want it to be passed by ref, then pass by ref. And if you don't care, then use auto ref. const ref just isn't needed. But since it precedes auto ref, we have it. And until auto ref works with non-templated functions, const ref is still needed. - Jonathan M Davis