Do we really need const?
Bruce Adams
tortoise_74 at yeah.who.co.uk
Mon Sep 17 11:04:07 PDT 2007
Jarrett Billingsley Wrote:
> "Bill Baxter" <dnewsgroup at billbaxter.com> wrote in message
> news:fcl79k$18vu$1 at digitalmars.com...
>
> > It seems from the discussion here the past week, there is no real
> > multithreading benefit to be had from const/invariant. 'Pure' is where
> > it's at for that. So maybe we're just better off without the complexities
> > of const. I've certainly gotten used to the lack of const in Python, so
> > why not in a C++-ish language?
>
> I start to wonder how much of the "of COURSE we need const!" thinking comes
> from "if all you have is a hammer, everything starts looking like a nail."
> That is, I wonder how many people think we absolutely need const because
> they're so used to using it in C and C++.
>
> Never having learned a const-correct language (started with various BASICs,
> then on to very rudimentary C++, then D, and also a bit of Java and C#), I
> simply don't see the overwhelming need. Sure, there are a very few cases
> where const could be useful in my code for efficiency's sake, but I've never
> felt like I was missing any expressive power. Furthermore, I have been
> bitten exactly once by something that theoretically could have been
> prevented by const. It took me two minutes in the debugger to track down
> the problem. I'd say that those two minutes were a much better tradeoff
> than the god-knows-how-long it'd take to write const and non-const overloads
> of who-knows-how-many functions.
>
The problem with this is it isn't easy to tell how many problems would have been prevented if you are a regular user of const because they've been prevented. One exercise to try would be to take a large project and replace const with an empty string and see what the code looks like, then count the number, type and severity of potential errors relating to this absence. The problem is that doesn't take into account the dynamic nature of programming. Far more mistakes occur during development than you might be able to find in a finished product.
An example of one that catches me out quite often is:
strcpy(src,dest) vs. strcpy(dest,src);
As soon as src is const and dest mustn't be this can be caught at compile time. Granted that example is academic as I use std::string in
place of char*s whenever possible.
So that's one use case in favour of const parameters.
What happened to that "deconstructing the christmas tree" thread?
Gathering the useful use cases of constness together sounds like a good way forward to me.
Regards,
Bruce.
More information about the Digitalmars-d
mailing list