두 개의 로컬 정적 변수가있는 함수 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의
- 소멸자가 호출되는
# 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는 힙에 저장됩니까? 저장되지 않은 경우 어디에 저장됩니까?
't3 '은'test' 객체에 대한 원시 포인터입니다.'test' 객체 자체가 아니므로 소멸자는 자동으로 호출되지 않습니다. –
좋습니다, 정적 t3은 이름이고 메모리 영역에 대한 포인터입니다. 소멸자를 호출하고 메모리를 확보하는 방법은 무엇입니까? 힙 객체를 가리키는 정적 포인터를 생성하는 것이 설계상의 결함입니까? – Sree
항상 "스마트 포인터"를 사용하여'new'에 의해 할당 된 메모리의 소유권을 관리하십시오. 이 경우'unique_ptr'이 좋은 선택입니다 : http://en.cppreference.com/w/cpp/memory/unique_ptr. –