我已经从运算符T *()返回指针对象类型,并通过智能指针调用删除操作符,并尝试调用成员函数,并且我没有任何运行时错误。这怎么可能?或者我的理解是错误的?请建议。删除智能指针,但仍可以访问指针?
#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 ();
}
OUTPUT:
Display API x is 100
Inside T*()
Display API x is 100
[停止偷酒店房间钥匙!](http://stackoverflow.com/a/6445794/46642) – 2013-02-21 14:15:39
如果你的问题是:“为什么每次我调用UB时都不会UB崩溃”,那么答案是:“因为它的UB” – PlasmaHH 2013-02-21 14:16:53
你正在做一些你不允许的事情。询问期望什么没有意义。 – 2013-02-21 14:22:17