我有一个名为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
- 我的问题是
- 为什么会调用局部静态变量t1的析构函数,但不会调用局部静态变量t3的析构函数?
- t3和t1的存储期限是什么?
- t1存储在堆栈上,t2存储在堆上吗?如果不是,它们存储在哪里?
t3
是指向test
对象的原始指针 - 它本身不是一个test
对象,因此析构函数不会自动调用。 - Michael Burrnew
分配的内存所有权时,始终使用“智能指针”。在这种情况下,unique_ptr
是一个不错的选择: http://en.cppreference.com/w/cpp/memory/unique_ptr。 - Alan Stokes