gpt4 book ai didi

c++ - 智能指针无法释放内存

转载 作者:太空狗 更新时间:2023-10-29 20:04:49 28 4
gpt4 key购买 nike

<分区>

我的智能指针实现如下所示,它不会在异常时释放内存..

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**

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com