const?? When and why? This is ugly!
Denis Koroskin
2korden at gmail.com
Mon Mar 2 08:16:14 PST 2009
On Mon, 02 Mar 2009 06:28:24 +0300, hasen <hasan.aljudy at gmail.com> wrote:
> 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.
>
I you don't understand something, it doesn't mean something is wrong with the language. Perhaps, something wrong with you.
Regarding this exaple:
char[] p = "world";
It is rejected for a reason. Modifying the "world" through p will cause a segfault anyway. So it *must* be const. In case it won't, it will cause bugs that are even worse to track:
// file 1
char[] a = "hello";
a[4] = '!';
// file 2
writefln("hello"); // prints 'hell!'
More information about the Digitalmars-d
mailing list