const(FAQ)
Jason House
jason.james.house at gmail.com
Tue Apr 1 09:05:07 PDT 2008
Janice Caron Wrote:
> On 01/04/2008, Jason House <jason.james.house at gmail.com> wrote:
> > This is actually a good way to think about this stuff. My current problem with the const regime is that global variables can be used to break the transitive const nature.
>
> I think you are incorrect. In a class such as the following
>
> int g;
>
> class C
> {
> int * p;
>
> this()
> {
> p = &g;
> }
> }
>
> Then g cannot be modified through a const(C).
>
> const C c = new C;
> *c.g = 4; /*ERROR*/
>
> What you're talking about is something different. You're talking about
> a member function which is declared const accessing global variables.
> (Or at least, so I assume). Well, that's not a violation of anything.
> A /const/ function gets a read-only view of "this", but can still read
> and write global variables. A /pure/ function cannot see global
> variables at all.
You're right, I'm talking about a non-pure const function having access to global variables.
> > I really hate to see designs that encourage use of global variables!
>
> Every (non-pure) function ever can have some paramters const and
> others not. For member functions, one of those parameters happens to
> be "this", but that has no bearing on whether or not global variables
> are seen as const.
>
> Nothing "encourages" you to use global variables. However, rest
> assured that in the future, it will be possible to declare functions
> "pure", which will render global variables completely inaccessible.
I have to disagree. Global variables are a back door that allows a head-const-like behavior. This could include classic logging examples or objects to draw on a screen. Using a global variable can achieve this stuff, but in many cases that's bad design. What if I want my logging to be done differently depending on which object does the logging? Or different objects to be drawn to different locations?
It's the asymmetry that irks me. How is access to a global variable any different than access to a member object (with a final reference)?
More information about the Digitalmars-d
mailing list