ref const(T) the same as C++'s const T&?

Jonathan M Davis jmdavisProg at gmx.com
Tue Feb 15 11:55:32 PST 2011


On Tuesday, February 15, 2011 11:48:25 Peter Alexander wrote:
> Do D const references work the same as C++'s?
> 
> i.e.
> - Can they bind to rvalues?
> - Do they extend the life of rvalues?
> 
> If they do, are there any differences from C++?
> 
> If they don't, how do I pass large structs into a function efficiently?

The only bind to lvalues. A ref is a reference to a variable, so normal ref has 
to be passed a variable. In C++, it was decided that const& was special and 
could take a temporary. In D, it's no different from ref except that it's const, 
so it can't be changed. There have been requests to fix this, but Andrei is 
adamant that it was a huge mistake in C++ to do it since it makes it so that you 
can't determine whether a const& is really a rvalue or an lvalue. I don't know 
enough to know how much that really matters, but apparently it causes problems. 
The result is that D doesn't do that, which can be rather annoying when trying 
to pass temporaries to functions which take const ref, but that's the way it 
goes.

If you want to pass a large struct to a function efficiently, and you know that 
function isn't going to need to alter the struct, make it const ref. That way, 
it's const, and it doesn't get copied. However, that means that you can't pass 
temporaries to it. However, if you need to pass a temporary, then you're going 
to have to actually assign it to a variable first.

I _thought_ tht you could define a cost ref version and a non-const ref version 
and it would call the const ref version on lvalues and the non-const ref version 
on rvalues, but when I just tried it, it seems to call the non-const ref version 
in both cases. I don't know if that's a bug or not. But if you just have a const 
ref version, and you create a variable where you'd normally use a temporary, 
you'll be fine.

- Jonathan M Davis


More information about the Digitalmars-d mailing list