Does the 'with' statement affect object lifetime?
Ali Çehreli
acehreli at yahoo.com
Tue Jun 19 10:51:09 PDT 2012
Is the following code legal for a class?
class C {
int i;
}
void main() {
with(new C()) {
i = 42; // <-- Is the anonymous object alive at this point?
}
}
The object seems to live long enough for a class. That's probably
because the garbage collector kicks in late. But consider the same code
with a struct:
import std.stdio;
struct S {
int i;
this(int i = 0)
{
writeln("constructed");
}
~this()
{
writeln("destructed");
}
}
void main() {
with(S(1)) {
writeln("inside 'with' statement");
i = 42; // <-- Is the anonymous object alive at this point?
}
}
The output indicates that the anonymous object is destroyed before the
body of the with is executed:
constructed
destructed
inside 'with' statement
This contradicts with with's spec:
http://dlang.org/statement.html#WithStatement
It says that
with (expression)
{
...
ident;
}
is semantically equivalent to:
{
Object tmp;
tmp = expression;
...
tmp.ident;
}
Bug?
Ali
--
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html
More information about the Digitalmars-d-learn
mailing list