[comp.lang.c++] const and caching

vaughan@puma.cad.mcc.com (Paul Vaughan) (11/28/89)

	Consider the method A::foo(), where foo() conceptually does
not change any aspect of the A object, but does cause some information
to be cached, so that the next time A::foo() is called, it will return
(the same result) sooner.  Of course, the compiler won't let me
declare A::foo() to be const because it writes to a slot in the A
object, and it would clearly not work if this object were stored in
ROM.  The only solution I can think of is to have both a const version
and a non-const version available, where the const version will always
be slow.  Any comments?


 Paul Vaughan, MCC CAD Program | ARPA: vaughan@mcc.com | Phone: [512] 338-3639
 Box 200195, Austin, TX 78720  | UUCP: ...!cs.utexas.edu!milano!cadillac!vaughan

dog@cbnewsl.ATT.COM (edward.n.schiebel) (11/29/89)

From article <4289@cadillac.CAD.MCC.COM>, by vaughan@puma.cad.mcc.com (Paul Vaughan):
> 
> 	Consider the method A::foo(), where foo() conceptually does
> not change any aspect of the A object, but does cause some information
> to be cached, so that the next time A::foo() is called, it will return
> (the same result) sooner. 

I have the same problem with const.  I view it as "constant from the
outside" while the language (currently ? :-) considers it as
"constant through and through and no data may change". The way I have
gotten around it is to cast away constness on this. e.g.:

void A::foo() const
{
	// change some cached value
	(foo*)this->cached_value = new_value;
}

This works as long as the compiler didn't decide to put your A into
some deluxe read only memory, in which case the results are
undefined.  For my money, I think this is a reasonable compromise.

	Ed Schiebel
	AT&T Bell Laboratories
	dog@vilya.att.com
			

carroll@paul.rutgers.edu (V. I. Lenin) (11/29/89)

To reiterate Ed's point (not because I have anything new to add, but
merely because a good point deserves to be said several times in
several different ways):

	To C++, "const" means "concrete state const-ness."

	To the programmer, "const" should be used to mean
	"abstract state const-ness."

This is of course reasonable, since the compiler has no way of
knowing what you intend the abstract state of your objects to be.
What this means in practice is that C++'s understanding of "const"
is only a tool to be used by the programmer to implement the intended,
abstract meaning of "const."  This usually amounts to adding a few
casts here and there.

martin