https://issues.dlang.org/show_bug.cgi?id=13116
Issue ID: 13116 Summary: Should not be able to return ref to 'this' Product: D Version: unspecified Hardware: All OS: All Status: NEW Severity: normal Priority: P1 Component: DMD Assignee: nob...@puremagic.com Reporter: hst...@quickfur.ath.cx This code compiles, but should not: ----- import std.stdio; class C { int x; this(int _x) { x = _x; } ref C evil() { return this; // <-- should not compile but does } } void hmm(int x, int y, ref C c) { c = null; // corrupt memory writefln("%d %d", x, y); // prints "0 2" } void main() { auto c = new C(1); auto d = new C(2); hmm(1, 2, c.evil()); // N.B., we passed 1 and 2 to hmm() } ----- Explanation: C.evil() returns a dangling pointer to an out-of-scope local variable (i.e., 'this'), which is passed into hmm() which overwrites that memory location. On my system (Debian/Linux amd64) it just so happens that this memory location coincides with the address of the parameter 'x', thus causing x to get overwritten. Cause of bug: it should be illegal to return 'this' in a ref function, because it's a local variable (albeit implicit). --