Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite C++ code that uses mutable in D?

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?

like image 248
Arlen Avatar asked Dec 30 '11 05:12

Arlen


1 Answers

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.

like image 120
jA_cOp Avatar answered Jan 04 '23 17:01

jA_cOp