构造函数中的内存分配异常 [英] Memory Allocation Exception in Constructor

查看:158
本文介绍了构造函数中的内存分配异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个构造函数,使用 new 运算符分配几个内存块。

 code> X :: X(){
a = new int [100];
b = new char [100];
c = new float [100];我的问题是,如果分配 c <$ c



$ b 失败,并且构造函数抛出异常, a b 的内存将自动 和<$ c $

$

$

c> b
不会被自动释放。每个 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::vectors would obviate these problems.

这篇关于构造函数中的内存分配异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆