Summary: Pure functions as initializers for immutable
           Product: D
           Version: D2
          Platform: Other
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: DMD

--- Comment #0 from Tomasz SowiƄski <> 2010-10-19 11:49:42 
PDT ---
>From my post on D newsgroup:

Initializing immutable structures is a source of constant grief. Anything
non-trivial requires instancing a mutable structure, initializing it, and then
either casting to immutable (it's up to you to ensure no alias leaked) or, not
to violate the type system, duplicate the whole.

Yet, if there was a situation where the alias leaking is under control, casting
would be safe. Perhaps pure* functions are such a place. They can only touch
the immutable world, whether through globals or through their parameters. So if
one initializes the returned structure with a reference to the outside world,
it will be immutable. And if you stuff the structure with anything mutable, it
must have been created within the function's body, so no alias leaks.

I think it is safe to implicitly convert a pure function's return value to

* here by pure I mean either the old pure** when it still had immutable
arguments, or Don's "immutably pure".

Pure functions could be used as follows:

pure T make(Args args) { ... }
unittest {
    T t = make(...); // good
    immutable T t = make(...); // also good

Michel Fortin also noticed a nice-to-have: if at the call site you know that
all the arguments you're feeding the function with are immutable, then you can
automatically cast the result to immutable, even if the function can also
accept const arguments.

Configure issuemail:
------- You are receiving this mail because: -------

Reply via email to