Static member functions
Denis Koroskin
2korden at gmail.com
Tue Dec 8 10:53:52 PST 2009
On Tue, 08 Dec 2009 21:46:02 +0300, Michal Minich
<michal.minich at gmail.com> wrote:
> Discussion with Tomek Sowiński and Steven Schveighoffer moved from
> digitalmars.D.learn:
>
> Currently it is impossible to have static member function in struct or
> class; this does not compile:
>
> struct S2
> {
> static void foo () immutable { }
> }
>
> Error: function main.S.foo without 'this' cannot be const/immutable
>
> The problem I see is in definition of immutable member function:
>
> from D specs: "Immutable member functions are guaranteed that the
> object and anything referred to by the this reference is immutable." --
>
> I think this rule is wrong, because it mentions *this* and at the same
> time it applies to static member functions, which obviously doesn't have
> *this* reference.
>
> I propose changing this rule 2 to: "Immutable *non-static* member
> functions are guaranteed that the object and anything referred to by the
> this reference is immutable." and adding this one: "Immutable static
> member functions are guaranteed that the static variables of object and
> anything referred to by these variables is immutable"
>
> And I'm asking if this is reasonable, useful, implementable and/or
> desired - Or how should be defined semantics of static immutable member
> function? Currently there are none.
>
> Consider this example:
>
> struct S
> {
> static int x;
>
> static void foo () immutable
> {
> x = 3; // should be error, because immutable static member
> function cannot change mutable static data members.
> }
>
> static void bar ()
> {
> x = 3; // ok
> }
> }
>
> There is already bugzilla entry: http://d.puremagic.com/issues/
> show_bug.cgi?id=3598
--vote;
You idea doesn't generalize to other language components. Apart from
static members, there are global variables. Do you suggest that all free
functions that don't modify global state should also be marked as
immutable? What does it give?
AFAIK, immutable member functions can freely modify global state (not to
be confused with pure functions). As such, they can access non-immutable
static class function and there is no reason to have this qualifier.
OTOH, if you want to protect yourself from (accidental) global state
mutation, you are free to declare your static function as pure:
struct X
{
static int x;
static void foo() pure
{
// x = 3; // error
}
static void bar()
{
x = 3; // okay
}
}
As a result, I don't see any point for introduction static function
qualifiers. This is also inconsistent with ordinary member functions:
const/immutable applies to "this" pointer, passed to these functions as
hidden parameter. Static functions have no "this" and as such
const/immutable make no sense for them.
More information about the Digitalmars-d
mailing list