immutable promise broken in unions?

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jan 2 04:07:31 PST 2016


On Saturday, 2 January 2016 at 10:04:47 UTC, Shriramana Sharma 
wrote:
> import std.stdio;
> union EarthLocation
> {
>     struct { immutable double lon, lat, alt; }
>     double[3] data;
> }
> void main()
> {
>     EarthLocation d = {data: [4, 5, 6]};
>     writeln(d.data);
>     d.data = [1, 2, 3];
>     writeln(d.data);
> }
>
> I get the output:
>
> [4, 5, 6]
> [1, 2, 3]
>
> I thought the promise of `immutable` was: never changes, 
> whether via this interface or otherwise. How does then the 
> above work?
>
> Using DMD 2.0.69.2 on Kubuntu 64 bit.

You are manually breaking immutable by making a union of 
immutable and mutable data and then writing to the mutable 
reference. This is roughly equivalent to casting away immutable 
and then writing to the reference. It's a bug in your code.

All references to the same data should be
1) either immutable or const
or all the references should be
2) either mutable or const (assuming the data was never 
immutable).
Anything else is dangerous.


More information about the Digitalmars-d-learn mailing list