我从运算符T*()返回切入点类型,并通过智能指针调用delete操作符,并尝试调用成员函数,并且没有任何运行时错误。那件事怎么可能?还是我的理解错了?请给我建议。
#include <iostream>
using namespace std;
template <typename T>
class sPtr
{
private:
T * pointee__;
public:
operator T * () {
cout <<"Inside T* () "<<endl;
return pointee__;
};
explicit sPtr ( T * t )
{
pointee__ = t;
};
T * operator->() {
return pointee__;
}
};
class JTest
{
private:
int x;
public:
JTest ( int l=100) { x=l; };
void display ();
};
void JTest::display()
{
cout <<"Display API x is "<<x<<endl;
}
void JFunc (JTest * tmp)
{
cout <<" JFunc"<<endl;
tmp->display ();
cout <<"Invoking JTest -> display "<<endl;
}
int main ( int argc, char ** argv)
{
sPtr <JTest> t(new JTest);
t->display();
delete t; // Invokes operator T* () , and it is dangerous!!!..
t->display ();
}输出:
Display API x is 100
Inside T* ()
Display API x is 100发布于 2013-02-21 14:22:49
删除t将t指向的内存标记为未使用,但将存储在t中的地址保持不变。当您尝试使用存储在t上的对象时,C++不会检查它是否已被删除,因此,虽然您所拥有的对象经常会崩溃,但如果已删除对象所使用的内存尚未被系统覆盖,它可能偶尔会工作。
简而言之:有时这会奏效,经常会崩溃,这总是个坏主意。
如果您想保护自己免受自己的伤害,请在删除它之后将其设置为空。
https://stackoverflow.com/questions/15004460
复制相似问题