2015-01-02 4 views
1

두 개의 로컬 정적 변수가있는 함수 f()가 있는데 그 중 하나 (t3)는 동적으로 할당 된 메모리를 가리키고 다른 하나는 정상적인 t1 (스택에 할당 된 것 같습니다)입니다.로컬 파괴 정적 변수

#include <iostream> 
#include <string> 
using namespace std; 

class test 
{ 
public: 
    test(const char *name): _name(name) 
    { 
      cout << _name << " created" << endl; 
    } 
    ~test() 
    { 
      cout << _name << " destroyed" << endl; 
    } 
    string _name; 
    static test tc; // static member 
}; 
test test::tc(".class static data member"); 

test gvar("..global non-static object "); 
static test sgvar("...global static object"); 

void f() 
{ 

    static int num = 10 ; // POD type, init before enter main function 
    static test tl("..Local static object on (stack???)"); 
    static test* t3 = new test("..Local static object in free store"); 
    test t2("...local non-static object....."); 
    cout << "Function executed" << endl; 
} 

int main() 
{ 
    cout << "----------------------Program start----------------------" << endl; 
    test t("LocalToMain non-static object"); 

    f(); 

    cout << "----------------------Program end-------------------------" << endl; 
    return 0; 
} 

나는 called.Why되지 않은 지역 정적 (T3)에 대한 다음 내 질문이 지역 정적 T1의

  1. 소멸자가 호출되는

    # main               
    .class static data member created          
    ..global non-static object created          
    ...global static object created           
    ----------------------Program start----------------------    
    LocalToMain non-static object created         
    ..Local static object on stack created         
    ..Local static object in free store created       
    ...local non-static object..... created         
    Function executed              
    ...local non-static object..... destroyed        
    ----------------------Program end-------------------------    
    LocalToMain non-static object destroyed         
    ..Local static object on stack destroyed        
    ...global static object destroyed          
    ..global non-static object destroyed         
    .class static data member destroyed 
    
    • 출력하지만, 소멸자를 얻을?
    • t3 및 t1의 저장 기간은 얼마나됩니까?
    • t1은 스택에 저장되고 t2는 힙에 저장됩니까? 저장되지 않은 경우 어디에 저장됩니까?
+0

't3 '은'test' 객체에 대한 원시 포인터입니다.'test' 객체 자체가 아니므로 소멸자는 자동으로 호출되지 않습니다. –

+0

좋습니다, 정적 t3은 이름이고 메모리 영역에 대한 포인터입니다. 소멸자를 호출하고 메모리를 확보하는 방법은 무엇입니까? 힙 객체를 가리키는 정적 포인터를 생성하는 것이 설계상의 결함입니까? – Sree

+1

항상 "스마트 포인터"를 사용하여'new'에 의해 할당 된 메모리의 소유권을 관리하십시오. 이 경우'unique_ptr'이 좋은 선택입니다 : http://en.cppreference.com/w/cpp/memory/unique_ptr. –

답변

2

우선이는 C++ 사양은 실제로 로컬 (정적 또는 비 정적) 변수가 저장되는 위치에 대한 아무 말도하지 않습니다, 그것은 컴파일러에게 달려 있습니다. 귀하의 질문에 대해서는

변수 t3이 파괴이지만, 파괴되고 포인터이 아니라 무엇을 가리키는입니다. 당신이 delete 객체가 아니기 때문에 당신은 new이 실행 시간에 의해 파괴되지 않으며, 메모리는 "새어 나올 것"입니다.

t1t3의 수명 시간은 모두 프로그램의 평생 시간입니다.

그리고 t1이 저장되어 있는데, 아마도 특별한 데이터 세그먼트가 메모리에로드되었을 것입니다. 그러나 t2은 대부분의 컴파일러가 스택에 저장하는 일반 로컬 변수입니다.

예를 들어 numt1. 로컬 정적 변수는 유형에 관계없이 다른 로컬 정적 변수와 같습니다.