Topic: proposal !const (not const): example
Author: sjm@bnr.ca (Stuart MacMartin)
Date: Mon, 5 Apr 1993 18:44:01 GMT Raw View
In article <1993Apr3.185723.8852@mole-end.matawan.nj.us> mat@mole-end.matawan.nj.us writes:
>In article <1pgr7c$lf5@minotaur.cssc-syd.tansu.com.au>, gregw@cssc-syd.tansu.com.au (Greg Wilkins) writes:
>>
>> I have a problem with const. Currently, when an object is const -
>> absolutely none of its members may be modified, or non-const member
>> functions called. ... ... What const should prevent you from doing is
>> modifying members that represent the Value(big V) of the object, but ...
>> not ... from modifying the ... of members used for implementation.
>
>> Thus it is awkward to implement classes that have some form of lazy
>> evaluation of generated data. ...
>
>It's under consideration by x3j16/WG21 already.
Here's the case I hit:
I had a class which encapsulated a type of file, basically, and wanted
to disable certain methods if earlier errors were hit. I did this by
recording in each object that such errors had been hit. This resulted
in all methods being non-const because all could invoke a method that
would change the error state. That is, the methods are const unless
an error is encountered.
I could not see any way around this short of having a pointer to a
non-const value. I found that solution made me uneasy, so I ended
up removing "const" everywhere.
What should I have done?
Stuart
--
== Stuart MacMartin sjm@bnr.ca Bell-Northern Research, Ottawa, CANADA
== Standard disclaimers apply
Author: maxtal@physics.su.OZ.AU (John Max Skaller)
Date: Tue, 6 Apr 1993 16:57:59 GMT Raw View
In article <1993Apr5.184401.11253@bcrka451.bnr.ca> sjm@bnr.ca (Stuart MacMartin) writes:
>
>Here's the case I hit:
>
>I had a class which encapsulated a type of file, basically, and wanted
>to disable certain methods if earlier errors were hit. I did this by
>recording in each object that such errors had been hit. This resulted
>in all methods being non-const because all could invoke a method that
>would change the error state. That is, the methods are const unless
>an error is encountered.
>
>I could not see any way around this short of having a pointer to a
>non-const value. I found that solution made me uneasy, so I ended
>up removing "const" everywhere.
>
>What should I have done?
>
You can cast away const. This is probably correct.
You can also CHEAT!
class X {
X* cheat;
int error;
public:
X() { cheat=this; } // loophole in type system
void g() const { ...
cheat->error=1;
}
};
This is somewhat cleaner than the cast away const notation,
but is still explicit when you are cheating.
--
JOHN (MAX) SKALLER, INTERNET:maxtal@suphys.physics.su.oz.au
Maxtal Pty Ltd, CSERVE:10236.1703
6 MacKay St ASHFIELD, Mem: SA IT/9/22,SC22/WG21
NSW 2131, AUSTRALIA