what operator(s) should I overload to prevent this?

drug drug2004 at bk.ru
Mon Oct 16 12:30:39 UTC 2017


16.10.2017 15:18, Biotronic пишет:
> On Monday, 16 October 2017 at 12:00:13 UTC, drug wrote:
>> I refactored `MyStructure` added own implementation of malloced array 
>> based on pureRealloc/pureFree instead of dynamic array I used before 
>> and now I have error:
>> Error: cannot implicitly convert expression get(msg.getData()) of type 
>> const(MyStructure) to MyStructure.
>>
>> What operators should I overload to let this conversion? I've tryed 
>> opCast and it fails in other call sites, also I've tried opAssign - it 
>> didn't works, what worked is wrapping in ctor - MyStruct(const_var). 
>> But using ctor is not convenient.
> 
> The reason this doesn't work is you have some sort of non-immutable 
> pointer, reference or array in your struct. I'm not sure why this worked 
> before, since I have no idea what your code looks like. Hence, I can 
> only give limited advice. Notably, the reasons this gives you a warning 
> is because it would be unsafe to do a simple cast.
> 
> You might have turned immutable(T)[] into T[] (where T is int, byte, 
> char, what-have-you). If this is the case, consider why this happened, 
> and try to turn it back into immutable(T)[]. The same goes for 
> immutable(T)*. Remember that an alias can make something immutable, so 
> it might not be immediately obvious.
> 
> If you're fine with being unsafe, and can't find a solution like the 
> above, consider this:
> 
> struct MyStruct {
>      MyStruct getUnsafe() const {
>          return cast(MyStruct)this;
>      }
>      alias getUnsafe this;
> }
> 
> -- 
>    Biotronic

Hmm, I started to write reduced case and probably found the reason - 
I've changed slice to const data by slice to mutable data. Will 
investigate further. Thank you for your answer!


More information about the Digitalmars-d-learn mailing list