Const ref and rvalues again...

Timon Gehr timon.gehr at gmx.ch
Wed Nov 7 02:33:04 PST 2012


On 11/07/2012 04:13 AM, martin wrote:
> On Wednesday, 7 November 2012 at 02:58:57 UTC, Era Scarecrow wrote:
>> Maybe a very simple change/addition; Like perhaps @ref? (Attribute
>> ref, Alternate ref, auto ref.. All sorta fit for it's meaning).
>>
>> So...
>>
>> void func1(ref int x);  //D lvalue-only ref
>> void func2(@ref int x); //works like c++'s ref
>>
>> Seems fairly easy to tell apart, and still leaves const-ness as an
>> option.
>
> Afaik C++ doesn't allow rvalues to be passed to _mutable_ references
> (T&), only to const references, making perfect sense imo. I really do
> not see the point for an additional syntax for C++-like const references
> (const T&) which would also take rvalues.

You are still missing that const in C++ is different from const in D.
Also, if the point is to have higher speed, why shouldn't the function 
be allowed to use an rvalue as scratch space without a _deep copy_ ?

const in C++ does not mean anything. It is just loosely enforced 
interface documentation. const in D actually restricts what the callee 
can do with the argument, in a transitive fashion.

> Please give me an example where you want to pass an rvalue to a
> _mutable_ reference parameter.


When my struct does not support any operations that are const, and 
creating a mutable copy is not possible due to indirections?

> I would simply continue to disallow that,
> since that would mean that changes to the referenced rvalue would not be
> visible for the caller (a temporary/literal is changed - how could
> someone possibly want that?).

The change may well be visible...

class C{
     int x;
}
struct W{
     C c;
}

W createW(C c){ return W(c); }
void foo(ref W w){ w.c.x = 2; }

void main(){
     C c = new C;
     assert(c.x==0);
     foo(createW(c));
     assert(c.x==2);
}


More information about the Digitalmars-d mailing list