From slices to perfect imitators: opByValue

Artur Skawina via Digitalmars-d digitalmars-d at puremagic.com
Sat May 10 08:27:19 PDT 2014


On 05/09/14 01:05, Sönke Ludwig via Digitalmars-d wrote:
> Am 09.05.2014 00:02, schrieb Timon Gehr:
>> On 05/08/2014 06:30 PM, Sönke Ludwig wrote:
>>> Am 08.05.2014 18:10, schrieb Timon Gehr:
>>>> On 05/08/2014 06:02 PM, monarch_dodra wrote:
>>>>>
>>>>> If you have const data referencing mutable data, then yes, you can cast
>>>>> away all the const you want, but at that point, it kind of makes the
>>>>> whole "const" thing moot.
>>>>
>>>> This is not guaranteed to work. I guess the only related thing that is
>>>> safe to do is casting away const, but then not modifying the memory.
>>>
>>> For what practical reason would that be the case? I know that the spec
>>> states "undefined behavior",
>>
>> Case closed.
> 
> Bonus points for getting the difference between "practical" and "theoretical"...

It's not just theoretical. This D program:

   void main() {
      const a = 1;            // The same program works w/ "auto a = 1;"
      auto p = cast(int *)&a;
      ++*p;
      import std.stdio;
      writeln(a);             // Oops. What if this was the refcount?
      writeln(*p);
   }

is enough to see that 'const' vs 'auto' actually affects the result;
no need for a mythical sufficiently advanced compiler.

Yes, todays compilers often do not take advantage of the const info
when an indirection is involved - this is because it's then harder to
prove that there are no other (mutable) aliases to the data. (This is
one reason for the "malloc" function attribute; unique-expressions will
also help)

artur


More information about the Digitalmars-d mailing list