Binding rvalues to const ref in D

bitwise via Digitalmars-d digitalmars-d at puremagic.com
Thu Oct 20 10:13:50 PDT 2016


On Wednesday, 19 October 2016 at 15:18:36 UTC, Atila Neves wrote:
> [...]
> On the one hand some people want rvalues to bind to const ref. 
> I can only assume that they want this because they want to pass 
> rvalues to a function efficiently
> [...]
>
> struct Vector { float x, y, z; }

In games/real-time simulations, we have to deal with 4x4 
float/double matrices. They're not big enough to warrant a heap 
alloc(like opencv's cv::Mat) but not small enough that you want 
to arbitrarily copy them around either. When you have a scene 
with thousands of nodes, all the extra copying will be a huge 
waste.

I cringe every time I see someone getting all religious about 
profilers. There isn't always one big thing that's responsible 
for your slowdown.


> The situation is this: if one wants move semantics, one must 
> know when one can move. Because rvalues bind to const& in C++, 
> you never know whether the const& is an lvalue or rvalue. The 
> solution to this was rvalue references, which are refs that can 
> _only_ bind to rvalues. That way you know that the origin was 
> an rvalue an wahey, move semantics. They complicated the 
> language significantly. Did you know there's more than one kind 
> of rvalue in C++? Oh yes:

I don't understand the situation completely here.

void foo(ref Bar bar){}
void foo(Bar bar){}

Why do these have to be ambiguous? Can't the compiler just prefer 
the second overload for rvalues?

In C++, you _must_ differentiate between move constructors and 
by-value constructors because of the eager copying that happens 
when you pass things like std::vector by value. I suggested a 
similar convention for D containers though, and Andrei was 
strongly opposed to the idea of eager-copying value-type 
containers. If things go this way, then aren't the above two 
overloads enough?

     Bit




More information about the Digitalmars-d mailing list