我有一个函数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
发布于 2015-01-02 06:03:06
首先,C++规范实际上没有提到本地(静态或非静态)变量的存储位置,而是取决于编译器。
至于您的问题,变量t3已被销毁,但它是被销毁的指针,而不是它指向的指针。由于您不delete对象您的new,它将不会被破坏的运行时,内存将“泄漏”。
t1和t3的生命周期是程序的生命周期.
我不知道t1存储在哪里,可能是在一个加载到内存中的特殊数据段中,但是t2是一个正常的局部变量,大多数编译器都存储在堆栈上。
实际上,num和t1之间并没有太大的区别。本地静态变量与任何其他局部变量一样,无论类型如何。
https://stackoverflow.com/questions/27737975
复制相似问题