Problems with D const ref vs C++ const &

Jonathan M Davis jmdavisProg at gmx.com
Fri Dec 10 14:47:33 PST 2010


On Friday, December 10, 2010 14:31:34 Piotr Szturmaj wrote:
> Craig Black wrote:
> > In C++ I could to the following:
> > 
> > Vector3 cross(const Vector3 &a, const Vector3 &b) { ... }
> > 
> > and then call it like this:
> > 
> > Vector3 a, b, c;
> > a = cross(b, c);
> > a = cross(b-a, c-a);
> > 
> > But in D I have to define two functions if I want pass by reference to
> > work:
> > 
> > Vector3 cross(ref const Vector3 a, ref const Vector3 b) {...}
> > Vector3 cross(Vector3 a, Vector3 b) {...}
> 
> Isn't const for that (without ref)?
> 
> Vector3 cross(const Vector3 a, const Vector3 b) {...}
> 
> In this case, compiler should pass const by reference (since it will not
> change).

The compiler doesn't just make things references. You have to tell it to. If you 
have a const parameter which is a value type, it's just going to be a const 
local variable. It's not going to be a reference to anything no matter what that 
means for efficiency (though structs are supposedly supposed to be cheap to copy). 
Now, if Vector3 were a class, then it's always a reference. But that's because 
it's a reference type.

- Jonathan M Davis


More information about the Digitalmars-d mailing list