pure factory function vs immutable(Foo)**

drug via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 10 08:42:04 PDT 2017


10.07.2017 17:57, ag0aep6g пишет:
> I feel like I must be missing something here.
>
> This works:
>
> ----
> alias T = int;
>
> T** f(const T** input) pure
> {
>     T** output;
>     return output;
> }
>
> void main()
> {
>     T i;
>     T* p = &i;
>     immutable T** r = f(&p);
> }
> ----
>
> `f` is `pure`, its parameter is const, and its return type has mutable
> indirections. That makes it a "pure factory function" [1].
>
> Since `f` is a pure factory function, the compiler can assume that the
> result is not referenced from anywhere else. So I can declare it
> `immutable`.
>
> So far, so good.
>
> Now change `T` to `alias T = immutable int;`. The program gets rejected.
> The error message is: "cannot implicitly convert expression (f(& p)) of
> type immutable(int)** to immutable(int**)".
>
> What changed? `f` can now return a reference to `i`. But that's not a
> problem, because that part of the return type is already `immutable`.
> What would be a problem is if `f` could return a reference to `p`. But
> it can't, as far as I can tell.
>
> Am I missing something or could/should the program be accepted with `T =
> immutable int`? What could `f` do that would break `r`'s immutability?
>
>
> [1] https://dlang.org/spec/function.html#pure-functions
I'm not sure I understand, but
```
immutable (T)** r = f(&p);
```
compiles. So compiler complains that indirections are mutable, but 
immutable ones are expected according to type of `r`



More information about the Digitalmars-d-learn mailing list