Const ref and rvalues again...

Timon Gehr timon.gehr at gmx.ch
Wed Nov 7 13:39:51 PST 2012


On 11/07/2012 07:48 PM, martin wrote:
> 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)?

You can pass him an object that does not support operations you want to 
preclude. He does not have to _know_, that your book is not changed when 
he reads it. This is an implementation detail. In fact, you could make 
the book save away his reading schedule without him noticing.

> 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.
>

I'd assume that the book you pass him would not support changing the author.

>> 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.

Maybe, but the fact that we know it harms encapsulation.


More information about the Digitalmars-d mailing list