[英]Destruction of local Static variable
我有一個帶有兩個局部靜態變量的函數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;
}
我得到以下輸出
# 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
首先,C ++規范實際上沒有說明本地(靜態或非靜態)變量的存儲位置,而是由編譯器決定。
至於您的問題,變量t3
被破壞了,但是指針卻被破壞了,而不是它指向的對象。 由於您不delete
new
對象,因此運行時不會破壞它,並且內存將“泄漏”。
t1
和t3
的生命周期都是程序的生命周期。
我不知道t1
的存儲位置,可能是在加載到內存的特殊數據段中,但是t2
是大多數編譯器都存儲在堆棧中的普通局部變量。
num
和t1
之間確實沒有太大區別。 無論類型如何,局部靜態變量都與任何其他局部靜態變量一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.