Transitive const sucks

Steven Schveighoffer schveiguy at yahoo.com
Tue Sep 11 10:48:51 PDT 2007


"Janice Caron" wrote
> On 9/11/07, Steven Schveighoffer <schveiguy at yahoo.com> wrote:
>> "Janice Caron" wrote
>> > What all of these use-cases have in common is the fact that the state 
>> > is
>> > private
>> >
>> > Suppose that all class and struct members which were declared private,
>> > were always mutable,
>> > even if the class instance is const.
>>
>> I sort of agree with you,
>
> I believe I can make the case for my argument stronger. In general,
> when I expose a class's interface, the understood contract is:
>
> class C
> {
>     public:
>         /* stuff I want you to know about */
>
>     private:
>         /* None of your gorram business. It's PRIVATE.
>            You shouldn't care know or care what's in here */
> }

Yeah, I understand your original point.  I'm not disputing that, which is 
why I "sort of" agree with you.  My point that protected should be able to 
be mutable as well as private was the point I was trying to make.

>> but what about instances where you want derived
>> classes to be able to access the cache?
>
> I can't think of a use-case for that.

The one that comes to mind is if you wanted to slightly modify the way a 
cache was used.  The two options are: make the cache protected, and allow 
derived classes to use it (in which case mutable is required), or 
re-implement the cache in the slightly modified way in the derived class, in 
which case you are carrying around 2 caches for no reason.

> Would it not suffice for the base-class to expose protected functions
> to provide read-only access to the cache?

Well, yeah, you could do it that way, but you would have to know before-hand 
how your cache was going to be accessed/used by the derived classes, 
therefore restricting the creativity of the author of the derived class.

>> What is the argument against mutable again?
>
> In C++, you can do this:
>
> class C
> {
> public:
>     mutable int x;
>     C() { x = 0; }
>     void f() const { x = 5; }
> }
>
> main()
> {
>     const C c;
>     printf("%d\n", c.x); /* prints 0; */
>     c.f();
>     printf("%d\n", c.x); /* prints 5; */
> }
>
> This is clearly nonsense.
>
// tango style
class NonsenseInD
{
  private int _x = 0;
  int x() const { return _x;}
  void f() const { x = 5;}
}

// could be in another file
int main(char[][] args)
{
  const NonsenseInD c = new NonsenseInD;
  Stdout(c.x).newline; // prints 0;
  c.f();
  Stdout(c.x).newline; // prints 5;
}

Even with this example, I still don't see why mutable is such a horrible 
thing...  To me it makes sense to have pieces of a class that can change, 
even when the class is const.  You have given several good examples (files, 
net connections, etc), but I think your idea of enforcing public data being 
const is probably not feasible.

-Steve 





More information about the Digitalmars-d mailing list