Frustrations with const
Timon Gehr
timon.gehr at gmx.ch
Thu Mar 8 12:00:19 PST 2012
On 03/08/2012 08:49 PM, H. S. Teoh wrote:
> On Thu, Mar 08, 2012 at 08:22:05PM +0100, Timon Gehr wrote:
>> On 03/08/2012 08:09 PM, H. S. Teoh wrote:
> [...]
>>> The problem is, how to write this function so that it can be called from
>>> *both* a const public method and a non-const public method? Since the
>>> method itself doesn't actually modify anything, it *should* in theory be
>>> possible to mark it as const:
>>>
>>> const Slot *findSlot(Key key) { ... }
>>>
>>> However, because the const applies to 'this', the compiler insists that
>>> referencing anything via 'this', including reading a pointer to a slot,
>>> must also be const, so it refuses to let the return type be Slot*; it
>>> has to be const(Slot)*.
>>>
>>> But this is silly, because now the caller isn't allowed to modify the
>>> Slot either, so now I need to bloat the code with two identical copies
>>> of findSlot, one with const, and one without (since if it wasn't marked
>>> const, then a const method couldn't call it).
> [...]
>> inout(Slot)* findSlot(Key key) inout { ... }
>
> Ahhh. Thanks!
>
> But that still doesn't solve the problem:
>
> inout(Slot)* findSlot(Key key) inout {
> auto slot = slots[hash(key)];
inout(Slot)* slot = slots[hash(key)];
> while (slot) {
> if (slot.hash == hash(key)&& slot.key == key)
> return slot;
>
> // Error: cannot modify inout(Slot)*
> ---> slot = slot.next;
> }
> return null;
> }
>
>
>
> T
>
More information about the Digitalmars-d-learn
mailing list