作者dreamroad (我身在未来)
站内Programming
标题Re: 请问C++ Class中 const static object 的life …
时间Fri Sep 19 02:30:15 2008
这种写法会... compile error
型别不对
所有const static member data会在main function之前完成初始化的动作
在main function结束之前被消灭
但是你是用指标 指向一个匿名的暂时物件
虽然会指标会初始化 指标会消灭
但是它所指向的暂时物件不会被消灭
所以在你的程式结束之前
你要自行想办法把这个东西delete掉
要不然在某些系统可能造成memory leak.
如下:
#include <string>
using namespace std;
class C {
private:
const static string* foo;
public:
static void KillFoo()
{
delete foo;
}
};
const string* C::foo = new string("hello");
int main()
{
//your code
//...
//when you want to kill foo, maybe in the last line of your code
C::KillFoo();
//never use foo hereafter...
}
========================================================
你也可以写个小程式测试一下到底static member data什麽时候会占记忆体
什麽时候被消灭...
#include <cstdio>
class Something
{
public:
Something() { printf("constructor\n"); }
~Something() { printf("destructor\n"); }
};
class C {
const static Something foo;
};
const Something C::foo = Something();
int main()
{
printf("start\n");
printf("main funciton\n");
printf("end\n");
}
==============
constructor
start
main function
end
destructor
==============
※ 引述《sorryChen (陈扬和)》之铭言:
: 想要在class中定义一个const static object. 就说string
: 如果在
: Class C {
: const static string* foo;
: }
: const string foo = new string("hello");
: 请问这个string何时被产生(占记忆体)何时被消灭呢
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 203.67.8.224