Problem overloading operator for a struct with an immutable member

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 25 21:55:26 PDT 2015


On Tue, 24 Mar 2015 16:49:01 +0000, Nicolas Sicard wrote:

> I don't know if this is a bug or expected behaviour. The struct is
> mutable, assignable and pre-increment operator works. But post-increment
> doesn't compile because of the immutable member.
> 
> --
> struct S {
>      int i;
>      immutable(Object) o;
> 
>      S opUnary(string op)() { return this; }
>      void opAssign(S other) {}
> }
> 
> void main()
> {
>      S s, t;
> 
>      t = s; // OK ++s; // OK s++; // Error: cannot modify struct s S
>      with immutable members
> }

yes, this is a bug. it happens due to compiler rewrite rule (postfix 
operation is rewritten to expression like 'auto tmp = var; ++var; tmp', 
but before this compiler tries to check if `var` is modifiable lvalue.

i.e. for prefix increment compiler FIRST checks for operator overload, 
and only THEN checks for modifiable lvalue (if there is no overload).

but for postfix increment compiler FIRST checks for modifiable lvalue, 
and only THEN tries to rewrite expression and find operator overload.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150326/1049ff72/attachment.sig>


More information about the Digitalmars-d-learn mailing list