const/immutable on delegates
Tofu Ninja via Digitalmars-d
digitalmars-d at puremagic.com
Thu Jul 2 17:26:38 PDT 2015
So this idea spawned from a thread I posted over in learn[1].
Similar to how you can mark a member function as const or
immutable, there should be a way to mark a delegate as const or
immutable.
For a member function, marking it const/immutable means the this*
will be const/immutable. For a delegate, marking it
const/immutable should mean that the context* will be
const/immutable. This already happens for delegates to member
functions, but I think this would be valuable for all delegates
in general.
Const on a delegate would just implicitly convert everything in
the context to const.
ie:
void foo()
{
int x = 4;
auto bar = () const
{
x++;// error, x is const
};
x++;// Ok
}
Immutable on a delegate would require every thing in the context
to be immutable. Because you can't just implicitly convert to
immutable this means any variable use in the context must be
immutable.
ie:
void foo()
{
int x = 4;
immutable int y = 4;
auto bar = () immutable
{
return x;// error, x is not immutable
};
auto bar2 = () immutable
{
return y;// Ok
};
}
One of the benefits of the immutable attribute would be to ensure
strong purity on delegates. For instance currently a delegate
marked pure could still change if either A) it modifies its own
context, or B) the function that created the context still has
not returned and it modifies the context. Being able to annotate
it as const fixes A, being able to annotate it as immutable fixes
both A and B.
Thoughts?
[1]
http://forum.dlang.org/thread/dpyncfsfjinwjvkzeomk@forum.dlang.org
More information about the Digitalmars-d
mailing list