Best practices for logical const

Steven Schveighoffer schveiguy at yahoo.com
Sat Feb 15 19:26:41 PST 2014


On Sat, 15 Feb 2014 22:17:48 -0500, Meta <jared771 at gmail.com> wrote:

> On Sunday, 16 February 2014 at 03:16:16 UTC, Steven Schveighoffer wrote:
>> On Sat, 15 Feb 2014 22:04:25 -0500, Meta <jared771 at gmail.com> wrote:
>>
>>> Obviously this is extremely contrived, but inout is effectively  
>>> logical const here. Is there no way to know what the "original"  
>>> mutability of t is at compile-time?
>>
>> No, because only one version of the function is generated. That is part  
>> of the benefit of inout over a template.
>>
>> If you DO want to know whether it's mutable, use a template.
>>
>> -Steve
>
> If you pass a mutable value to a function taking an inout parameter,  
> what's the difference between that function and an identical function  
> that takes a regular mutable parameter instead of an inout parameter?

I'm not sure what you are asking, because the answer I want to give is so  
trivial :)

Identical functions produce identical code. Const, inout, immutable,  
whatever, these do not change code generation, just what is allowed to  
those variables.

The rational behind inout came from the strstr problem:

const char *strstr(const char *haystack, const char *needle);

1. You want the signature of strstr to guarantee it will not change it's  
parameters.
2. You do not want strstr to change the CALLER's permissions on the  
parameters, which it effectively does by applying const to the return  
value.

I want the result of strstr to have the same restrictions as the parameter  
I pass in (mutable, const or immutable). The only way to do this was with  
a template. But a template would generate 3 separate versions of strstr  
with the exact same code in it. Maybe an enterprising compiler can elide  
the 2 superfluous versions, but there's another problem -- the mutable  
version would be able to change the parameter! We gave up on item 1.

inout does this correctly, and it makes a world of difference in accessors  
of structs and classes.

-Steve


More information about the Digitalmars-d mailing list