Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static destructor

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!

like image 392
anon Avatar asked Feb 17 '10 05:02

anon


1 Answers

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).

like image 111
GManNickG Avatar answered Oct 11 '22 09:10

GManNickG