Stupid scope destruction question

Denis Shelomovskij verylonglogin.reg at gmail.com
Thu Sep 20 02:27:44 PDT 2012


Is there any guaranties that `ScopeTemp` will not be destroyed before 
`f` call because it isn't used?
---
struct ScopeTemp
{
     ...
     // allocates value
     this(...) { ... }

     @property void* value() { ... }

     // destroys value
     ~this() { ... }
}

void f(void* ptr) { ... }

void main()
{
     f(ScopeTemp(...).value);
}
---
According to http://dlang.org/struct.html#StructDestructor
"Destructors are called when an object goes out of scope."
So I understand it as "it will not be destroyed before scope exit even 
if not used". Is it correct?

So the question is if `ScopeTemp`'s scope is `main` scope, not some 
possibly generated "temp scope" (don't now what documentation statements 
prohibit compiler from doing so).


Working code:
---
import std.exception;
import std.c.stdlib;

struct ScopeTemp
{
     private int* p;
     // allocates value
     this(int i)
     in { assert(i); }
     body { *(p = cast(int*) enforce(malloc(int.sizeof))) = i; }

     @disable this(this);

     @property int* value() { return p; }

     // destroys value
     ~this() { *p = 0; p = null; /*free(p);*/ }
}

void f(int* ptr)
{
     assert(*ptr == 1);
}

void main()
{
     f(ScopeTemp(1).value);
}
---
-- 
Денис В. Шеломовский
Denis V. Shelomovskij


More information about the Digitalmars-d-learn mailing list