If you needed to rewrite the following C++ code in D, how would you do it?
struct A{
const S* _s;
B _b;
C _c;
mutable C _c1, _c2;
A(const B& b, const C& c, const S* s){ /*...*/ }
void compute(const R& r) const
{
//...
_c1 = ...
_c2 = ...
}
};
D doesn't have mutable
, and, based on my experience, it's rarely used in C++. But, assuming mutable
is used for the right reasons here, what are my options in D?
D's immutable
is transitive, when given an immutable reference (such as the this
reference in an immutable member function), all fields are immutable too. There is no way around this in D. const
only exists in D to bind mutable and immutable data, but since immutable is implicitly convertible to const, it has to be transitive too. Once you go immutable (or const), you can't go back.
The benefits are several: immutable data can be shared across threads safely, can be put in ROM if desirable, and is easy to reason with.
There simply is no room for logical const in D, for better or worse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With