static destructor

2019-04-06 09:53发布

问题:

Suppose I have:

void foo() {
  static Bar bar;
}

Does c++ guarantee me that Bar::Bar() is called on bar, and Bar::~Bar() is never called on bar? (Until after main exits).

Thanks!

回答1:

Yes. The first time foo() is called, Bar bar will be constructed. It will then be available until main() finishes, after which point it will be destructed.

It's essentially:

static Bar *bar = 0;
if (!bar)
{
    bar = new Bar;

    // not "real", of course
    void delete_bar(void) { delete bar; }
    atexit(delete_bar);
}

Note I said "essentially"; this probably isn't what actually happens (though I don't think it's too far off).


3.7.1 Static storage duration
1 All objects which neither have dynamic storage duration nor are local have static storage duration. The storage for these objects shall last for the duration of the program (3.6.2, 3.6.3).