z****e 发帖数: 2024 | |
t****t 发帖数: 6806 | 2 neng
【在 z****e 的大作中提到】 : 构造函数里能不能抛出异常?
|
z****e 发帖数: 2024 | 3 我说得不明白,
我是想说,这样做好不好?
因为如果:
A( ):_i(0){
int* p=new int[10];
throw(type1);
}
那么这个mem leak怎么办呢?
不知道问题问的对不对。
【在 t****t 的大作中提到】 : neng
|
p***o 发帖数: 1252 | 4 That's where you need an auto_ptr.
【在 z****e 的大作中提到】 : 我说得不明白, : 我是想说,这样做好不好? : 因为如果: : A( ):_i(0){ : int* p=new int[10]; : throw(type1); : } : 那么这个mem leak怎么办呢? : 不知道问题问的对不对。
|
z****e 发帖数: 2024 | 5 哦,原来这里是我们以前那个故事的结局?
除了auto_ptr没有其他解决办法了吗?
【在 p***o 的大作中提到】 : That's where you need an auto_ptr.
|
p***o 发帖数: 1252 | 6 Well, you can write your own, as long as the class frees the resource
upon destruction.
【在 z****e 的大作中提到】 : 哦,原来这里是我们以前那个故事的结局? : 除了auto_ptr没有其他解决办法了吗?
|
z****e 发帖数: 2024 | 7 but in the case i wrote, the constructor is not finished, so the destructor
will not be called, right?
【在 p***o 的大作中提到】 : Well, you can write your own, as long as the class frees the resource : upon destruction.
|
t****t 发帖数: 6806 | 8 dui
destructor
【在 z****e 的大作中提到】 : but in the case i wrote, the constructor is not finished, so the destructor : will not be called, right?
|
p***o 发帖数: 1252 | 9 class A
{
your_class obj_;
public:
A() : obj_(new int)
{
throw;
}
};
When A::A() throws, the compiler will make sure the 'partially'
constructed A will be 'partially' destructed. In this case,
the destructor of obj_ will be called, give you a chance to
release any resource acquired by obj_.
destructor
【在 z****e 的大作中提到】 : but in the case i wrote, the constructor is not finished, so the destructor : will not be called, right?
|
p***o 发帖数: 1252 | 10 Just want to let him know you mean A::~A() will not be called ;)
【在 t****t 的大作中提到】 : dui : : destructor
|
z****e 发帖数: 2024 | 11 明白了。
我理解是,如果一定要在ctr里边throw,而throw之前还要申请内存,就把那个要申请
内存的指针包装起来,不能是一个裸体指针,应该是一个被包装好的对象。例如auto_
ptr.
对吧。
【在 p***o 的大作中提到】 : Just want to let him know you mean A::~A() will not be called ;)
|
t****t 发帖数: 6806 | 12 1. stack unwinding will be performed.
2. result of 1: full constructed auto objects and subobjects will be full de
structed. partially constructed objects will not be destructed, but memory w
ill be released.
【在 z****e 的大作中提到】 : 明白了。 : 我理解是,如果一定要在ctr里边throw,而throw之前还要申请内存,就把那个要申请 : 内存的指针包装起来,不能是一个裸体指针,应该是一个被包装好的对象。例如auto_ : ptr. : 对吧。
|
z****e 发帖数: 2024 | 13 got it!
de
w
【在 t****t 的大作中提到】 : 1. stack unwinding will be performed. : 2. result of 1: full constructed auto objects and subobjects will be full de : structed. partially constructed objects will not be destructed, but memory w : ill be released.
|
O*******d 发帖数: 20343 | 14 用auto_ptr.
【在 z****e 的大作中提到】 : 我说得不明白, : 我是想说,这样做好不好? : 因为如果: : A( ):_i(0){ : int* p=new int[10]; : throw(type1); : } : 那么这个mem leak怎么办呢? : 不知道问题问的对不对。
|