const behaviour

Timon Gehr timon.gehr at gmx.ch
Fri Jun 22 03:32:23 PDT 2012


On 06/22/2012 12:25 PM, Namespace wrote:
> As far as i know "int" is not immutable or const by default.
> So, why work this code:
>
> [code]
> import std.stdio;
>
> class Bar {
>
> }
>
> class Foo {
> private:
>      int _id;
>
>      Bar _b;
>
> public:
>      this(int id, Bar b) {
>          this._id = id;
>
>          this._b = b;
>      }
>
>      // const_behaviour.d(18): Error: cannot implicitly convert
> expression (this._b) of type const(Bar) to const_behaviour.Bar
>      const(Bar) GetB() const pure nothrow { /// <- must be const(Bar)
> instead of Bar
>          return this._b;
>      }
>
>      int GetId() const pure nothrow { /// <- no const(int) is
> neccessary. Why?!
>          return this._id;
>      }
> }
>
> void main() {
>      Bar b = new Bar();
>
>      Foo f = new Foo(42, b);
> }
> [/code]

The same reason, because const(int) implicitly converts to int. If the
data is copied, the qualifiers can be changed in any way that is
desired. As string, int has no mutable indirections.


More information about the Digitalmars-d-learn mailing list