digitalmars.D.learn - Zombie Object?
- Namespace (35/35) Feb 07 2013 [code]
- monarch_dodra (19/54) Feb 07 2013 Well, given that you are reading a deleted/destroyed object, I'm
- Namespace (2/2) Feb 07 2013 Ah thank you.
[code] import std.stdio; class Vec2 { public: short x, y; this(short x, short y) { this.x = x; this.y = y; } } void foo(Vec2 v) { delete v; } void bar(Vec2 v) { } void main() { foo(new Vec2(42, 23)); Vec2 v1 = new Vec2(4, 2); foo(v1); assert(v1 !is null); writefln("v1.x = %d", v1.x); Vec2 v2 = new Vec2(4, 2); bar(v2); writefln("v2.x = %d", v2.x); } [/code] This code prints: v1.x = 0 v2.x = 4 But is this correct? I expected v1.x = 4 v2.x = 4 Same behaviour with destroy.
Feb 07 2013
On Thursday, 7 February 2013 at 10:15:49 UTC, Namespace wrote:[code] import std.stdio; class Vec2 { public: short x, y; this(short x, short y) { this.x = x; this.y = y; } } void foo(Vec2 v) { delete v; } void bar(Vec2 v) { } void main() { foo(new Vec2(42, 23)); Vec2 v1 = new Vec2(4, 2); foo(v1); assert(v1 !is null); writefln("v1.x = %d", v1.x); Vec2 v2 = new Vec2(4, 2); bar(v2); writefln("v2.x = %d", v2.x); } [/code] This code prints: v1.x = 0 v2.x = 4 But is this correct? I expected v1.x = 4 v2.x = 4 Same behaviour with destroy.Well, given that you are reading a deleted/destroyed object, I'm not sure why you'd expect *any* behavior at all. I'd simply expect *undefined* behavior... In any case, I think what you are seeing is a Vec2 instance init state. If you change Vec2 to: //---- class Vec2 { public: short x = 2, y = 2; // ... //---- Then the output becomes: v1.x = 2 v2.x = 4 AFAIK, the delete/destroy *might* eagerly reset the object to its init state, to make future re-use more efficient. I'm not sure, but in any case, what you are observing is undefined, so I wouldn't look too much into it...
Feb 07 2013