thoughts on immutability in D

Jonathan M Davis jmdavisProg at gmx.com
Fri Sep 23 17:31:12 PDT 2011


On Friday, September 23, 2011 17:13 Walter Bright wrote:
> On 9/23/2011 4:13 PM, Jonathan M Davis wrote:
> > But while C++'s const is not as good as D's const, it's still very
> > worthwhile IMHO.
> 
> To me it's like buffer overflows. 99% of C/C++ code doesn't have buffer
> overflows, and is perfectly reliable. But if someone hands you a 1,000,000
> line program and asks "ensure there are no buffer overflows" what are you
> going to do? What are you going to do when Junior Programmer makes a patch
> to your perfectly correct C/C++ code base, and now it has a subtle
> overflow bug? Start all over with the review process?
> 
> This is not an idle question, as a major focus of C static analysis tools
> is to detect buffer overflows, and people spend a lot of effort & money on
> them.
> 
> Faith based programming works in the small, but programs grow ever larger
> in size and complexity. Switching from faith to static guarantees is a
> much more scalable technique.
> 
> And where C++ const is really, really useless is when it comes to
> multithreaded programming.

No, C++ does not give you an ironclad guarantee about correctness, and yes, 
it's absolutely useless for multi-threaded programming, but what it _does_ 
give you is still valuable. For instance, if I choose to use const_iterator 
instead of iterator, then when I screw up the call to <algorithm>'s copy 
function and mix up the iterators, the compiler will catch it and complain. 
When I try and call a non-const function on a const object, the compiler will 
complain. It will help me find errors in my code. And no, it won't help me 
find every const-related error, and no, there is no absolute guarantee that a 
const function _won't_ alter the object, but in general, it actually doesn't 
alter the object, and I have to specifically circumvent the compiler to be 
able to alter const stuff. Certain classes of bugs are caught because of const 
in C++. Even if the compiler can't take advantage of it for optimizations or 
whatnot, and even if it doesn't give as strong guarantees to the programmer as 
might be desirable, it _does_ help the programmer catch and prevent bugs.

I completely agree with you that having static guarantees is better, but I 
don't think that the faith-based guarantees of C++'s const are worthless, just 
worse.

- Jonathan M Davis


More information about the Digitalmars-d mailing list