"<Type> is not mutable" when using ref return type

Mehrdad wfunction at hotmail.com
Wed May 18 21:52:45 PDT 2011


On 5/18/2011 9:22 PM, Jonathan M Davis wrote:
> On 2011-05-18 20:55, %u wrote:
>> Hi!
>>
>> Is this a bug, or is it intentional that this fails? I can't come up
>> with any case where it would cause a problem, but the compiler doesn't
>> like the fact that there's a const in the structure:
>>
>>      struct Temp { const int a; int b; }
>>
>>      auto ref foo(Temp* t) { return *t; } //Error
> As soon as you do *t, you're copying the value. As such, I don't know why the
> ref is working at all. And it's impossible to assign to a struct with a const
> or immutable member, so the struct is not mutable. Why that's a problem
> here... My guess would be that it's a bug relating to copying from or
> assigning to const. If you declare this(this), you'll notice that it doesn't
> currently work with const, and if declared, this(this) would be called upon
> copying the struct. Still, something like
>
> auto t = Temp();
> auto u = t;
>
> works with your definition of Temp, so just copying a non-mutable struct works
> as long as it doesn't declare this(this). It's probably treating auto ref as
> if it must be mutable or something like that, and Temp isn't. But I don't know
> what the problem is exactly.
>
> In any case, I would definitely advise that you _not_ create structs with
> const or immutable values, because you can never reassign to them, which
> causes all kinds of fun problems - including making it very hard to use them
> in arrays (_any_ place that would use Temp.init is stuck with Temp.init). It's
> generally better to just make the variables private and provide @property
> functions for getting the variables but not provide any for setting them. That
> way, they're read-only and you can still re-assign the whole struct if need
> be.
>
> - Jonathan M davis

By the way, it doesn't matter if I use auto or not. It does the same 
thing if I say "ref Temp".

Interesting notes about postblit and everything, I'll keep those in 
mind, thanks!


More information about the Digitalmars-d mailing list