what's the scope of a static variable inside a local function?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Jan 5 22:07:27 UTC 2018


On Friday, January 05, 2018 16:59:38 Steven Schveighoffer via Digitalmars-d-
learn wrote:
> On 1/5/18 4:44 PM, Marc wrote:
> >> void foo() {
> >>     void baa() {
> >>         static int n;
> >>         writeln(n++);
> >>     }
> >> }
> >>
> >> void main() {
> >>  static int x;
> >>  foo();
> >>  doSomething(x);
> >> }
> >
> > does x and n has same lifetime, i.e, program's execution or n is longer
> > available onde foo() call reach out of scope?
>
> Both are the same. The lifetime is actually thread-local (one instance
> per thread).

Yeah, they're initialized at compile-time (unlike what you get in C++),
which means that you don't get all of that stuff about them being created
when the function is first called. And they live as long as the thread
lives. What I started wondering about when I saw this though was when the
destructors for local static variables get run, and it turns out that they
don't. This code

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

struct S
{
    this(string foo)
    {
        _foo = foo;
    }

    ~this()
    {
        writefln("%s destroyed", _foo);
    }

    string _foo;
}

void main()
{
    static mainStatic = S("main");
    auto s = S("local");
    f();
}

void f()
{
    static fStatic = S("f");
}
-------------------

prints out

local destroyed

but doesn't print out anything about main or f. I don't know if that's a bug
or not, since the only way that I can think of to make it work would be to
have the compiler invisibly add a static destructor to the module to clean
them up, and that would cause other problems. It's just not something that
I've ever thought about before.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list