const behaviour
Timon Gehr
timon.gehr at gmx.ch
Fri Jun 22 03:22:22 PDT 2012
On 06/22/2012 11:21 AM, Namespace wrote:
> Based to the current const discussions (once again) I wanted to appease
> my curiosity and want to ask why the following code works as described
> in the comments:
>
> [code]
>
> import std.stdio;
>
> class Bar { }
>
> class Foo {
> private:
> string _text;
>
> Bar _b;
>
> public:
> this(string text, Bar b) {
> this._text = text;
> this._b = b;
> }
>
> // const_behaviour.d(18): Error: cannot implicitly convert
> expression (this._b) of type const(Bar) to const_behaviour.Bar
> Bar GetB() const pure nothrow { /// <- must be const(Bar) instead
> of Bar
> return this._b;
> }
>
> string GetText() const pure nothrow { /// <- no const(string) is
> neccessary. Why?
> return this._text;
> }
> }
>
> void main() {
> Bar b = new Bar();
>
> Foo f = new Foo("foobar", b);
> }
>
> [/code]
string is immutable(char)[] and const(immutable(char)[]) implicitly
converts to immutable(char)[]. Or put differently, a string doesn't
have to be const-qualified because it cannot be changed anyway.
More information about the Digitalmars-d-learn
mailing list