AA and struct with const member

Era Scarecrow rtcvb32 at yahoo.com
Wed Dec 29 22:09:35 UTC 2021


On Wednesday, 29 December 2021 at 01:11:13 UTC, Stanislav Blinov 
wrote:
> Because opIndexAssign cannot distinguish at compile time 
> between initialization and assignment:
>
> ```d
> Stuff[Key] aa;
> aa[key] = Stuff(args); // ostensibly, initialization
> aa[key] = otherStuff;  // assignment to existing value
> ```
>
> Same syntax, different behavior. This can only be caught at 
> runtime. `require` and `update` though should be able to pull 
> this off, and that they don't is a bug.

So i wonder if const and immutable would have different behaviors 
then.

While you shouldn't be able to explicitly change a const item 
within a struct, replacing the whole struct i would think would 
be okay, on the basis that you're basically throwing whole old 
item away (*and may be equal to what you'd do with say swap*).

  Immutable on the other hand may want to refuse as it should 
basically have a lifetime of the array? Though if you can delete 
the item and then just add it in again it's a longer version of 
the same thing, just depends on if anything is using/referencing 
it or not. And casting away the constness is easy enough so maybe 
it won't be different.

  Though if it's a basic type it seems unlikely it would need a 
longer lifetime, and if it's a reference or array it already is 
separated from the struct and needs no such protection for the 
pointer.

  I don't know. I remember odd behavior with const/non-const stuff 
before.


More information about the Digitalmars-d-learn mailing list