static destructor

时间秒杀一切 提交于 2019-12-09 15:41: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).



来源:https://stackoverflow.com/questions/2278441/static-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!