Implicit conversion of struct with methods to immutable in pure function fails
Timoses
timosesu at gmail.com
Wed Jul 18 11:28:54 UTC 2018
On Tuesday, 17 July 2018 at 06:24:12 UTC, Simen Kjærås wrote:
>
> That makes sense. The problem is F has a context pointer to the
> main() block, since it's a non-static struct with methods
> inside a block. It doesn't actually use the context pointer for
> anything, so it possibly shouldn't have one, but it does, so we
> have to work around it.
>
> The fix is to mark F as static, or move it outside the main()
> block.
>
> --
> Simen
Thanks for the explanation.
But why is a context pointer a problem? Is it problematic because
the context pointer to the main scope can not guarantee
`immutable`? E.g. if I happened to use data from main in a
function of the immutable struct then... well then what?
The struct would still be immutable, but what would prevent a
function from using non-immutable data?
E.g. I could do this
int gnumber = 3;
struct F
{
int i;
void fun() immutable
{
gnumber = 5;
}
}
void main ()
{
immutable F f = F();
f.fun;
}
I declared `fun()` to be an immutable function. So calling the
immutable struct function `F.fun()` changes a module scope int.
The same could be applied to local data of the main scope,
however the following fails:
void main ()
{
int mnumber = 3;
struct F
{
int i;
void fun() immutable
{
// Error: immutable function onlineapp.main.F.fun
cannot access mutable data mnumber
mnumber = 5;
}
}
immutable F f = F();
f.fun;
}
Is this connected why I can't implicitly convert a local struct
with a context pointer to immutable? What's the reason behind it?
More information about the Digitalmars-d-learn
mailing list