c++함수 안에 static변수의 수명(lifetime)은 어떻게 되죠?
조회수 3343회
function의 scope안에서 정의된 static
변수는 한 번만 초기화되고 함수가 끝나도 계속 유지된다고 알고 있는데
정확한 lifetime은 어떻게 되나요?
생성자와 소멸자는 정확히 언제 호출되나요?
소스코드
void foo()
{
static string plonk = "When will I die?";
}
1 답변
-
function내의
static
변수의 life time은 코드가 처음으로 실행될 때 시작돼서 프로그램이 끝날 때 같이 끝납니다. 그리고 표준에 따르면static object
의 소멸자는 생성된 순서와 반대 순서로 실행되어야 합니다.예제:
struct emitter { string str; emitter(const string& s) : str(s) { cout << "Created " << str << endl; } ~emitter() { cout << "Destroyed " << str << endl; } }; void foo(bool skip_first) { if (!skip_first) static emitter a("in if"); static emitter b("in foo"); } int main(int argc, char*[]) { foo(argc != 2); if (argc == 3) foo(false); }
결과:
C:>sample.exe Created in foo Destroyed in foo C:>sample.exe 1 Created in if Created in foo Destroyed in foo Destroyed in if C:>sample.exe 1 2 Created in foo Created in if Destroyed in if Destroyed in foo
댓글 입력