const/immutable member functions
Jonathan M Davis
jmdavisProg at gmx.com
Mon Jan 24 06:20:17 PST 2011
On Monday 24 January 2011 05:56:49 Trass3r wrote:
> class F
> {
> const Foo bar();
> }
>
> Isn't this ambiguous? "returns a const Foo object" vs. "is a const
> member function that returns a Foo object"?
When using const or immutable in a function signature, it _always_ applies to
the function, unless you use parens to say otherwise.
const Foo bar(); //const function
Foo bar() const; //const function
immutable Foo bar(); //immutable function
Foo bar() immutable; //immutable function
const(Foo) bar(); //mutable function with const return value
const(Foo) bar() const; //const function with const return value
immutable(Foo) bar(); //mutable function with immutable return value
immutable(Foo) bor() immutable; //immutable function with immutable return value
And, of course, you could mix up const and immutable to have const functions
with immutable return values and vice versa.
Personally, I don't like it. In fact, most people don't, but that's the way it
is. I always put const and immutable or the right-hand side of the function when
I want the function to be const or immutable, and I wish that that were
required, but it isn't. It's the way it is because it's consistent with all of
the other function modifiers: @property, nothrow, public, static, etc. In fact,
ddoc always put them all in front of the function signature, even if you put
them after.
So, if you want the return value to be const or immutable, use parens. Otherwise
it's the function. If you want both to be const and/or immutable, then you need
to mark them both that way.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list