请教如果在类的静态函数中,调用delete 来删除自己,会发生什么
请问如果在类的静态函数中,调用delete 来删除自己,会发生什么?
假如代码片段如下:
class A
{
static void func();
}
void A::func()
{
delete this;
return;
}
请问这里的delete this会不会有问题?再进一步什么情况下有问题?
我感觉是如果delete this后没有对class中的成员变量的操作,应该是安全的。
欢迎大家来讨论。。。
------解决方案--------------------
代码你能编译过去么?
先编译过去再说
------解决方案--------------------
static成员函数和变量不是依赖与某个class实例的,static函数在class创建前就存在了,所以this指针在static函数里无法获得。编译就会出错。
------解决方案--------------------
呵呵,静态方法里面没什么this指针。
------解决方案--------------------
楼主是想创建Singleton模式类吧
下面是从网上找来的个人认为最好的方法
Solution2:
use static local variable instead of member variable(m_pInstance)
class Singleton ...{
public:
static Singleton& instance (); // return reference
void op1 ();
protected:
Singleton ();
Singleton (const Singleton&);
Singleton& operator = (const Singleton&);
};
...
Singleton& Singleton::instance () ...{
// created at first call; destructed after main
static Singleton instance;
// Local static object is automatically destructed after main
return instance;
}
------解决方案--------------------
静态不存在this
假如代码片段如下:
class A
{
static void func();
}
void A::func()
{
delete this;
return;
}
请问这里的delete this会不会有问题?再进一步什么情况下有问题?
我感觉是如果delete this后没有对class中的成员变量的操作,应该是安全的。
欢迎大家来讨论。。。
------解决方案--------------------
代码你能编译过去么?
先编译过去再说
------解决方案--------------------
static成员函数和变量不是依赖与某个class实例的,static函数在class创建前就存在了,所以this指针在static函数里无法获得。编译就会出错。
------解决方案--------------------
呵呵,静态方法里面没什么this指针。
------解决方案--------------------
楼主是想创建Singleton模式类吧
下面是从网上找来的个人认为最好的方法
Solution2:
use static local variable instead of member variable(m_pInstance)
class Singleton ...{
public:
static Singleton& instance (); // return reference
void op1 ();
protected:
Singleton ();
Singleton (const Singleton&);
Singleton& operator = (const Singleton&);
};
...
Singleton& Singleton::instance () ...{
// created at first call; destructed after main
static Singleton instance;
// Local static object is automatically destructed after main
return instance;
}
------解决方案--------------------
静态不存在this