Stupid scope destruction question

Denis Shelomovskij verylonglogin.reg at gmail.com
Thu Sep 20 02:33:08 PDT 2012


20.09.2012 13:27, Denis Shelomovskij пишет:
> 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);
> }
> ---

Wow, this `main` works fine too:
---
// same ScopeTemp definition as above

int* gptr;

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

void g()
{
     assert(*gptr == 0);
}

void main()
{
     f(ScopeTemp(1).value);
     // Here `ScopeTemp` value is already destroyed
     g();
}
---

So `ScopeTemp`'s scope definitely isn't a `main` scope. So the question: 
what do we know about this "temp scope"?

-- 
Денис В. Шеломовский
Denis V. Shelomovskij


More information about the Digitalmars-d-learn mailing list