这样的new有办法delete吗?
class A
{
};
void fun1(int i)
{
if(i==0)
{
throw new A;
}
if (i==1)
{
throw new A;
}
else
{
}
}
void fun2(int i)
{
try
{
fun1(i);
}
catch (A* e)
{
}
}
这样写的程序,fun2(0)是不是调用一次就内存泄漏一次?这样的new有办法delete吗?
另外,是不是每个new都要delete,要不一定会吃内存?——换句话说,有没有某种情况下,new之后没用delete也不内存泄漏?
分不是很多,技术交流,我在很多c++书上看到new之后没delete的。
[解决办法]
因为很多技术书上推荐用 catch (A &e),抛出时也不用new
[解决办法]
new了一定要delete。
你看的那些书仅仅是介绍某种例子,很小的程序,反正泄露了也无所谓,退出程序后操作系统会把内存收回来。
[解决办法]
- C/C++ code
#include <iostream>using namespace std;class A{public: ~A(){cout<<"destructor"<<endl;}};int func(int i){ if(i == 1) { throw new A; return 1; } else return 0;}int main(){ try{ func(1); }catch(A * pa) { delete pa; cout<<"deleted!"<<endl; } return 0;}