WTF did happen with struct constructor and ref in 2.061 ?

Jonathan M Davis jmdavisProg at gmx.com
Sat Jan 5 16:32:19 PST 2013


On Saturday, January 05, 2013 13:58:48 js.mdnq wrote:
> Nope, technically the "struct literal" does not go out of scope
> because it exists on the stack till the end of the outer scope...
> just as the local variable does. As I said, it is equivalent, due
> to the substitution principle to the hidden variable:
> 
> S s = S(2); foo(s) <==> foo(S(2))
> 
> because
> 
> foo(S(2)) can be shorthand for "hidden S __s = S(2); foo(s);"
> 
> (so, computationally these would all(or should) produce identical
> results).
> 
> You are saying because "visually" foo(S(2)) leaves the "scope" it
> is different than the others. This is true, but only visually(or
> syntactically). But the compiler could give you access to the
> hidden variable and then you would be wrong(it would not go out
> of scope).
> 
> Scope is not a physical but logical syntactical construct imposed
> by the compiler to help the user break a complex structure into
> nested units.

No offense. I'm afraid that you simply have no clue what you're talking about. 
Scope is defined by the language. And temporaries leave scope when the 
statement that they're in completes. And these examples in both D and C++ show 
that that's the case:

------------
import std.stdio;

struct S
{
    this(int i)
    {
        this.i = i;
        writeln("Constructed!");
    }

    ~this()
    {
        writeln("Destroyed!");
    }

    int i;
}

void foo(S s)
{
    writeln("foo!");
}

void main()
{
    writeln("before");
    foo(S(5));
    writeln("after");
}
------------

------------
#include <cstdio>
using namespace std;

struct S
{
    S(int i)
    {
        this->i = i;
        printf("Constructed!\n");
    }

    ~S()
    {
        printf("Destroyed!\n");
    }

    int i;
};

void foo(S s)
{
    printf("foo!\n");
}

int main()
{
    printf("before\n");
    foo(S(5));
    printf("after\n");

    return 0;
}
------------

They both print

before
Constructed!
foo!
Destroyed!
after

If the struct literal continued to exist after the call to foo, "Destroyed!" 
would have printed after "after," but it printed before "after" in both cases.

This is required by the language, and it's precisely why doing things like 
taking the address of a temporary are so incredibly foolish to do.

- Jonathan M Davis


More information about the Digitalmars-d mailing list