Const ref and rvalues again...

martin kinke at libero.it
Wed Nov 7 10:48:16 PST 2012


On Wednesday, 7 November 2012 at 18:07:27 UTC, Timon Gehr wrote:
> You do not give a justification.
>
>> I find it very useful to know that an argument
>> won't be modified.
>
> That is unrelated and does not necessarily follow, but that it 
> does in some cases is the main reason why const is useful even 
> though it weakens encapsulation.

Let's look at encapsulation this way: suppose my function is a 
colleague and his job is to summarize a book I lend him (my 
reference parameter). I don't care how he does it as long as the 
summary (function result) is what I expect. But I do care about 
my book if I plan on using it afterwards (so in case the argument 
is an lvalue used later on) - will I have to check it for 
defects, coffee spillings etc., or can I be sure it's exactly as 
it was before (const)? This is how I see it.
The thing about mutable rvalue references would be unknown or 
unthought-of side effects: what if the book is the same, but my 
colleague, a known psychopath, killed the author (a property of 
the book reference, a reference itself)? I don't use the book 
anymore, okay (it was an rvalue after all), but it may still be 
worth knowing that the author has gone. Due to the transitiveness 
of const, the (const) author would still be alive if the book 
reference had been const.

> You have to do that anyway if it the operation is not at least 
> 'const pure' and you need to guarantee that no other thread is 
> in fact modifying the data.

I think we can agree that knowing the parameters aren't touched 
does help a lot in this case.


More information about the Digitalmars-d mailing list