抛出异常的对象在堆栈,mem泄漏与新? [英] throwing exceptions of objects on the stack, mem leak with new?
问题描述
这是一个错误:
if(some_error)
throw Cat("Minoo");
其中Cat是类。
然后在一些其他函数中调用抛出异常的方法...
Then in some other function that called the method that threw the exception...
catch(const Cat &c)
{
}
如果无效,我使用新的Cat(Minoo);
If it is invalid, do I use new Cat("Minoo");
会导致内存泄漏吗?
推荐答案
?不,这正是你应该做的:抛出一个对象。 throw语句中的对象可以在堆栈上,但是在抛出时会被复制。比较,例如,执行返回Cat(Minoo)的效果;
1) Invalid? No, that's precisely what you're supposed to do: throw an object. The object in the throw-statement may be on the stack, but it is copied when it is thrown. Compare, for example, the effect of executing return Cat("Minoo");
2)会抛出一个指针,导致指向的对象被泄露吗?是的,如果对象是在堆上分配的,除非你安排删除它。但你应该避免将指针作为一般规则。
2) Will throwing a pointer cause the pointed-to object to be leaked? Yes, if the object was allocated on the heap and unless you arrange to delete it. But you should avoid throwing pointers as a general rule.
这篇关于抛出异常的对象在堆栈,mem泄漏与新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!