opAssign and const?

Jonathan M Davis jmdavisProg at gmx.com
Thu May 3 23:14:58 PDT 2012


On Friday, May 04, 2012 07:49:29 Era Scarecrow wrote:
>   I have the following dilemma. Hopefully I have this right.
> 
> struct X {
>    ref X opAssign(X x2);
>    ref X opAssign(ref X x2);
> }
> 
> X fn();
> 
> void func(){
>    X x, x2;
> 
>    x = x2; //uses ref
>    x = fn(); //without ref
> }
> 
>   According to the book, this is how it is suppose to be. const is
> a added promise not to modify anything. So... if i changed the
> ref to ref const... it won't call unless the item input was const
> as well.
> 
> //same as above except..
> struct X {
>    ref X opAssign(X x2);
>    ref X opAssign(ref const X x2); //const added
> }
> 
> void func(){
>    X x, x2;
>    const X x3;
> 
>    x = x2; //without ref???
>    x = x3; //ref
> }
> 
>   Since the input is intended to be read only anyways, why won't
> it work as expected with x = x2? This seems like a bug. If it's
> not, then I need to make two ref versions so it will behave
> properly. (If you need I can past actual working example)

I believe that the issue is that x2 isn't const, so when the compiler decides 
which of the two overloads to use, it picks the one which doesn't use const. 
If the const ref version were the only one, then it would work with x2, but 
since it isn't, the other one gets picked because it's deemed a better match.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list