Problems with D const ref vs C++ const &

Jonathan M Davis jmdavisProg at gmx.com
Fri Dec 10 15:29:48 PST 2010


On Friday, December 10, 2010 15:07:53 Piotr Szturmaj wrote:
> Jonathan M Davis wrote:
> > 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
> 
> Thank you for your explanations, I'm just learning D2. However, I meant
> something different: passing by reference was not strict ref in my mind,
> but some kind of address passing.
> This is done in Pascal/Delphi for more than decade. Variables passed as
> const parameters, are passed by address, to improve efficency, even if
> they're value types. Of course smaller builtin types like 32 bit integer
> doesn't get much advance. Const is supposed to be used with Vector3-like
> structs with floating point coordinates (12 bytes float, 24 bytes
> double), where it's better to not copy. Feel free to read first answer
> to this post:
> http://stackoverflow.com/questions/1600991/are-there-any-advantages-in-usin
> g-const-parameters-with-an-ordinal-type
> 
> Question is, if const parameters works similarly in D2?

I'm pretty sure that they don't, but someone more familiar with the compiler 
would have to say. I'm sure that it wouldn't be for shared variables (those 
would _have_ to be copied or it would change semantics), but I could see how 
that might be possible to do under the hood by the compiler for normal 
variables. I don't think that dmd does that though.

- Jonathan M Davis


More information about the Digitalmars-d mailing list