const?? When and why? This is ugly!

dsimcha dsimcha at yahoo.com
Sun Mar 1 20:45:17 PST 2009


== Quote from hasen (hasan.aljudy at gmail.com)'s article
> I haven't been following D for over a year .. now I notice there's a const!!
> In C++, in my experience, the only time I need const is when I pass
> temporary objects by reference and the compiler refuses, so I make the
> parameter const to make the compiler happy.
> void my_func( const SomeType& obj ) { ... }
> This is annoying because now const propagates like a virus! any function
> that I call on `obj` must also be changed to accept a `const` reference.
> any  method on obj which doesn't change it must also be marked as
> `const` in order for it to be callable from inside this function.
> This whole stupid process wouldn't even be needed in the first place if
> C++ had a garbage collector, because then I would always "new" them (as
> per Java, C#, and D)
> SomeType *obj = new SomeType();
> but because there's no garbage collector, I have to create the object
> not as a reference.
> SomeType obj();
> Again, this is all stupid C++ stuff that shouldn't even be needed in the
> first place.
> However, with all that being said, that's just my opinion, maybe over
> the time some people found some actually useful uses for const, great,
> so they can use it if they want.
> What really annoys me is the viral nature of const.
> Yesterday I was reading this: http://www.digitalmars.com/d/2.0/const3.html
> (btw, this page is empty: http://www.digitalmars.com/d/2.0/const.html )
> and, to my surprise, I see:
> char[] p = "world"; // error, cannot implicitly convert invariant
> 		    // to mutable
> and all I can think of is: WHAT - THE - HELL??!!!!!!
> invariant(char)[] is ugly! might as well be saying std::vector<char>
> (ok, not the best example of stupidity, but I hope you get my point).
> (and, is invariant(char)[] the correct type? or must it be
> invariant(char)[5]??)
> This is not the D that I loved. What's going on?
> P.S. look here
> http://stackoverflow.com/questions/557011/d-programming-language-char-arrays/
> I know you can use "auto" and all that, but still .. I don't feel good
> about this.

Uhh, that's what aliases are for.  The string alias is defined automatically in
object, and string is an alias for immutable(char)[].

Also, modulo a few library functions that use strings/immutable(char)[]s, when
they should be using const(char)[]s, one can avoid const by simply not using it if
one doesn't like it or doesn't need it for the program they're writing.



More information about the Digitalmars-d mailing list