STL中的vector,如果元素的构造函数抛出异常,会否出现资源泄露
答案:2 悬赏:30
解决时间 2021-02-14 01:09
- 提问者网友:独菊痴梦
- 2021-02-13 10:55
STL中的vector,如果元素的构造函数抛出异常,会否出现资源泄露
最佳答案
- 二级知识专家网友:冷眼_看世界
- 2021-02-13 11:41
#include <stdio.h>
#include <vector>
using namespace std;
struct A {
A() {
id = count++;
if (count == 5) {
throw "too many A";
}
}
A(const A&) {
id = count++;
if (count == 5) {
throw "too many A";
}
}
~A() {
printf("dtor of A, id = %d\n", id);
}
int id;
static int count;
};
int A::count = 0;
int main() {
try {
vector<A> a(10);
} catch (const char* str) {
printf("catched exception: %s\n", str);
}
return 0;
}vector的创建过程如果抛出了异常,会调用已经创建好的A的析构函数,所以A类保证析构正确释放资源就不会有泄露。当然,A的构造函数也应该保证不泄露资源。
#include <vector>
using namespace std;
struct A {
A() {
id = count++;
if (count == 5) {
throw "too many A";
}
}
A(const A&) {
id = count++;
if (count == 5) {
throw "too many A";
}
}
~A() {
printf("dtor of A, id = %d\n", id);
}
int id;
static int count;
};
int A::count = 0;
int main() {
try {
vector<A> a(10);
} catch (const char* str) {
printf("catched exception: %s\n", str);
}
return 0;
}vector的创建过程如果抛出了异常,会调用已经创建好的A的析构函数,所以A类保证析构正确释放资源就不会有泄露。当然,A的构造函数也应该保证不泄露资源。
全部回答
- 1楼网友:一身浪痞味
- 2021-02-13 12:32
元素的构造函数抛出异常,那你就去找和元素相关的东西,如果元素是系统资源,如GDI对象,内核对象,还有自己用new或malloc生成的内存空间,没有得到释放,那就会造成资源泄露或内存泄露,而且这和vector本身并没有太大关系,一般vector都会调用removeall或clear方法对vector容器进行清理。
再看看别人怎么说的。
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯