构造函数中的内存分配异常 [英] Memory Allocation Exception in Constructor
问题描述
我有一个构造函数,使用 new
运算符分配几个内存块。
code> X :: X(){
a = new int [100];
b = new char [100];
c = new float [100];我的问题是,如果分配c <$ c
$ b 失败,并且构造函数抛出异常, a
和 b
的内存将自动
和<$ c $
new []
必须与 delete []
明确平衡。 即使你的析构函数执行了删除(假设 a
, b
和 c
是类成员),那么你仍然会泄漏内存。
使用 std: :vector
s将会消除这些问题。
I have a constructor that allocates several blocks of memory using the new
operator.
X::X() {
a = new int[100];
b = new char[100];
c = new float[100];
}
My question is, if the allocation of c
fails, and the constructor throws an exception, will the memory for a
and b
be automatically freed?
The memory to which a
and b
point would not be automatically freed. Every new[]
must be balanced explicitly with a delete[]
.
Even if your destructor performed the deletion (assuming a
, b
, and c
are class members), then you'd still leak memory. That's because the destructor wouldn't be called in this case since the object failed to construct.
Using std::vector
s would obviate these problems.
这篇关于构造函数中的内存分配异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!