DIP 1018--The Copy Constructor--Formal Review
Walter Bright
newshound2 at digitalmars.com
Mon Feb 25 00:38:02 UTC 2019
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.
For example, most of DMD is written in the C++ style where functions frequently
are written to both return some information *and* tweak the data structure. This
does not work with const. It needs to be reorganized so that getting information
about a data structure is separated from modifying the data structure. I've made
such changes in a few places in DMD, and have been very pleased with the results
- the code is much easier to understand.
To sum up, you're quite right that you cannot write C++ style code using D
const. It hast to be in a much more FP style. If you're not accustomed with FP
style, this can be a difficult learning process. I know this from firsthand
experience :-)
For me the only real annoyance with const is I often cannot use "single
assignment" style declarations with pointers:
I.e.:
const int* p = &x;
p = &y; // error, good
*p = 4; // also error, not what I wished
This C++ const does provide, and it's good, but it's not really worth that much.
More information about the Digitalmars-d-announce
mailing list