why won't byPair work with a const AA?
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jul 29 22:48:33 PDT 2017
On 07/29/2017 10:15 PM, Matthew Gamble wrote:
>> I think it should work. I think a cast to unqualified is a safe
>> workaround in this case:
>>
>> auto pairs() @property const { return
>> (cast(int[string])aa).byPair.array.sort().release; }
As your question reveals, casting away const is not safe in general and
not for this code. :-/
> That works to solve the compile problem. Seems the data in aa was safe
> from modification without the const or casting, even if the values are
> reference types (i.e. ClassB[string]). Is that expected?
No, they are not safe as you can mutate values in the AA:
import std.stdio;
import std.array;
import std.algorithm;
class B {
int i;
void mutate() {
++i;
}
}
class A
{
this() { aa = ["a" : new B(), "b" : new B(), "c" : new B()]; }
auto pairs() @property const { return
(cast(B[string])aa).byPair.array.sort().release; }
private:
B[string] aa;
}
void main() {
auto a = new A();
auto p = a.pairs();
p.front[1].mutate();
assert(p.front[1].i == 1); // <-- Mutated :(
}
Of course, the problem is the same without const and the cast.
Ali
More information about the Digitalmars-d-learn
mailing list