问题描述
假设我有一个指向动态分配的10个元素数组的指针: T * p = new T [10] ;
稍后,我要发布该数组:
delete [] p;
如果其中一个 T
析构函数会发生什么抛出异常?其他元素还会被破坏吗?内存会释放吗?传播异常还是程序执行终止?
同样,当 std :: vector< T>
被销毁,其中一个 T
析构函数抛出?
p>我在标准中看不到明确的提示:
只是他们将以相反的创建顺序被调用
5.3.5删除[expr.delete]
即使抛出异常,内存释放也将被执行:
我在G ++中尝试了以下代码,它显示了没有更多的析构函数被调用例外:
#include< iostream>
int id = 0;
class X
{
public:
X(){me = id ++; std :: cout<< C:开始<我< \\\
;}
〜X(){std :: cout<< C:Done<<我< \\\
;
if(me == 5){throw int(1);}
}
private:
int me;
};
int main()
{
try
{
X data [10];
}
catch(...)
{
std :: cout<<< Finished\\\
;
}
}
执行:
> g ++ de.cpp
> ./a.out
C:Start0
C:Start1
C:Start2
C:Start3
C:Start4
C:Start5
C:Start6
C:Start7
C:Start8
C:Start9
C:完成9
C:完成8
C:完成7
C:完成6
C:完成5
完成
其中所有这些都回到这个(非常古老的答案):
Suppose I have a pointer to a dynamically allocated array of 10 elements:
T* p = new T[10];
Later, I want to release that array:
delete[] p;
What happens if one of the T
destructors throws an exception? Do the other elements still get destructed? Will the memory be released? Will the exception be propagated, or will program execution be terminated?
Similarly, what happens when a std::vector<T>
is destroyed and one of the T
destructors throws?
I can not see it explicitly called out in the standard:
Just that they will be called in reverse order of creation
5.3.5 Delete [expr.delete]
And that the memory deallocation will be done even if the exception is thrown:
I tried the following code in G++ and it shows that that no more destructors get called after the exception:
#include <iostream>
int id = 0;
class X
{
public:
X() { me = id++; std::cout << "C: Start" << me << "\n";}
~X() { std::cout << "C: Done " << me << "\n";
if (me == 5) {throw int(1);}
}
private:
int me;
};
int main()
{
try
{
X data[10];
}
catch(...)
{
std::cout << "Finished\n";
}
}
Execute:
> g++ de.cpp
> ./a.out
C: Start0
C: Start1
C: Start2
C: Start3
C: Start4
C: Start5
C: Start6
C: Start7
C: Start8
C: Start9
C: Done 9
C: Done 8
C: Done 7
C: Done 6
C: Done 5
Finished
Which all leads back to this (very old answer):
throwing exceptions out of a destructor
这篇关于如果删除[] p失败会怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!