On Wednesday, 22 July 2015 at 17:17:17 UTC, Frank Pagliughi wrote:
Or, to put it another way, getting threads out of the equation,
is this safe?
class MyThing { ... }
MyThing* create_a_thing() {
MyThing mt = new MyThing();
do_something_with(mt);
return &mt;
}
void main() {
MyThing* pmt = create_a_thing();
// ...
}
The "thing" will remain alive for the duration of main() ??
It is not safe, but for a different reason: `mt` is already a
_reference_ to the actual object (that's how classes behave in
D). This reference is located in a register or on the stack, and
`&mt` is therefore a pointer into the stack.
It's illegal to return that pointer from the function, because it
will become invalid once the function is left. Fortunately, the
compiler can detect simple cases like this one, and will refuse
to compile it:
Object* foo() {
Object o;
return &o;
}
xx.d(3): Error: escaping reference to local o