[Issue 23033] New: pure functions can allocate values with impure destructors
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Sun Apr 17 22:08:38 UTC 2022
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 at puremagic.com
Reporter: dkorpel at 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
}
```
--
More information about the Digitalmars-d-bugs
mailing list