On Monday, 25 February 2019 at 00:38:02 UTC, Walter Bright wrote:
The problem with C++ const is it only goes one level, i.e. what
I call "head-const". If you pass a T to a const parameter,
anything T references remains mutable. It's more of a
suggestion than anything reliable or enforceable. It only works
if your data structures are simple aggregates, not graphs.
D's const has teeth. Nothing can be modified through T. If
you're used to writing code that tweaks const data under the
hood, D's const will never work for you. Yes, it means
rethinking how the data and code is organized, and that can be
painful. But it is how FP works. FP offers a number of
advantages, and D's const offers a path into that.
I have no idea what people are talking about when they mention on
this forum that D's const is useless. Nearly every function
parameter in my code is `in`. Nearly every variable declaration
uses `const` instead of `auto`, the main exception being when a
function is constructing a value to return. Most member functions
I write are const or inout. I use const in D as I do in C++:
pretty much everywhere. Nearly every single time a function
parameter in my code isn't const is when it's an input range.
I happened to be working on dpp at the time I wrote this:
$ ag 'auto ' source | wc -l
67
$ ag 'const ' source | wc -l
204
The *only* problem I have with const in D is that const values
can't be copied, which is silly. I'd expect DIP1018 to fix that.