www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 23033] New: pure functions can allocate values with impure

https://issues.dlang.org/show_bug.cgi?id=23033

          Issue ID: 23033
           Summary: pure functions can allocate values with impure
                    destructors
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: normal
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: dkorpel live.nl

Came up here: https://github.com/dlang/dmd/pull/13993#issuecomment-1100944395

A pure function can allocate something with an impure destructor to violate the
assumptions a pure function gives, for example that the result of a pure
factory function is unique:
```
import core.memory;

char[] globalVar;

struct S
{
    char[] chars;
    ~this()
    {
        globalVar = chars;
    }
}

// pure factory function
char[] returnUnique() pure
{
    auto s = new S(new char[4]);
    s.chars[] = 'a';
    return s.chars;
}

void main()
{
    string s = returnUnique(); // safe cast to immutable
    GC.collect();        // impure destructor is run
    assert(s == "aaaa"); // string is immutable
    globalVar[] = 'b';   // alias escaped through impure destructor
    assert(s == "aaaa"); // we mutated immutable memory
}
```

--
Apr 17 2022