Frustrations with const

Steven Schveighoffer schveiguy at yahoo.com
Thu Mar 8 11:50:50 PST 2012


On Thu, 08 Mar 2012 14:49:12 -0500, H. S. Teoh <hsteoh at quickfur.ath.cx>  
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)];

What is type slot, and how is it constructed?  This snippit isn't enough  
to provide help.

> 		while (slot) {
> 			if (slot.hash == hash(key) && slot.key == key)
> 				return slot;
>
> 			// Error: cannot modify inout(Slot)*

An exact message is preferrable.

> --->			slot = slot.next;
> 		}
> 		return null;
> 	}

-Steve


More information about the Digitalmars-d-learn mailing list