我的智能指针实现如下所示,它不会在异常时释放内存..
template <class T>
class SMARTPOINTER
{
public:
SMARTPOINTER(T* pointee) : SMART_POINTEE(pointee) {
cout <<"\n Inside class SMARTPOINTER CONSTURCTOR \n";
}
~SMARTPOINTER() {
cout <<"\n Inside class SMARTPOINTER DESTRUCTOR \n";
delete SMART_POINTEE;
}
T& operator*() const
{
cout <<"\n Inside class SMARTPOINTER operator* \n";
return *SMART_POINTEE;
}
T* operator->() const
{
cout <<"\n Inside class SMARTPOINTER operator->() \n";
return SMART_POINTEE;
}
private:
T* SMART_POINTEE;
};
class Widget
{
public:
Widget() {
cout <<"\n Inside Widget CONSTRUCTOR \n";
}
void Fun() {
cout <<"\n Inside Widget::Fun() \n";
}
~Widget() {
cout <<"\n Inside Widget DESTRUCTOR \n";
}
};
class THROWME{
};
int main() {
SMARTPOINTER<Widget> sp(new Widget);
sp->Fun();
throw new THROWME;
(*sp).Fun();
return 0 ;
}
我发现输出是
Inside Widget CONSTRUCTOR
Inside class SMARTPOINTER CONSTURCTOR
Inside class SMARTPOINTER operator->()
Inside Widget::Fun()
uncaught exception of type THROWME*
Aborted.
据我所知,智能指针应该在这种情况下帮助我!!我没有发现通过智能指针调用 Widget 的破坏。
所以我必须在这里遗漏一些实现。
评论阅读后编辑
通过 try catch 我得到了我的结果。但我仍然不知道它的正确方法是否改变了代码
int main() {
try {
SMARTPOINTER<Widget> sp(new Widget);
sp->Fun();
THROWME tm;
throw tm;
(*sp).Fun();
}
catch(...) {
cout <<"\n **SOME EXCEPTION CAUGHT** \n";
}
return 0 ;
}
结果
Inside Widget CONSTRUCTOR
Inside class SMARTPOINTER CONSTURCTOR
Inside class SMARTPOINTER operator->()
Inside Widget::Fun()
Inside class SMARTPOINTER DESTRUCTOR
Inside Widget DESTRUCTOR
**SOME EXCEPTION CAUGHT**