如何在 C++ 中正确分配内存在内存不足的情况下
我看到资源显示了两种分配内存的方法,同时确保有足够的内存来完成操作。
1) 将“new”操作包装在 try/catch 中,因为它将返回 std::bad_alloc (?)
try { ptr = new unsigned char[num_bytes]; } catch(...) {}
2) 在“new”操作后检查分配的指针是否为 null。
ptr = new unsigned char[num_bytes]; if(ptr == NULL) { ... }
哪一个是正确的?他们都工作吗?我需要同时执行 1 和 2 吗?
谢谢,
jbu
I have seen resources show two ways of allocating memory while ensuring that there was enough memory to complete the operation.
1) wrap the 'new' operation in a try/catch since it'll return std::bad_alloc (?)
try { ptr = new unsigned char[num_bytes]; } catch(...) {}
2) check the assigned pointer for null after the 'new' operation.
ptr = new unsigned char[num_bytes]; if(ptr == NULL) { ... }
Which one is right? Do they both work? Do I need to maybe do both 1 and 2?
Thanks,
jbu
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用的是
new
的标准实现,它会抛出异常,那么第一个是正确的。如果您使用
nothrow
,则还可以使用第二个:If you are using the standard implementatin of
new
which throws exception, then first one is correct.You can also use the second one if you use
nothrow
as:不成功的分配[使用
new
]会抛出std::bad_aloc
,所以第一个是正确的。第二个用于c代码,当使用
malloc
时[由于C中没有异常,所以使用NULL来指示分配失败]。当使用 new 时,if 语句永远不会产生 true,因为如果分配失败,就会抛出异常,并且不会到达 if 语句。当然,当分配成功时,if 语句将返回 false。
a not successful allocation [using
new
] throwsstd::bad_aloc
, so the 1st is correct.the 2nd is used for c code, when using
malloc
[since there are no exceptions in C, NULL was used to indicate the allocation failed].when using
new
, the if statement will never yield true, since if the allocation failed - an exception will be thrown, and the if statement will not be reached. and of course when allocation is successful, the if statement will yield false.第二个习惯用法更适合
malloc
The second idiom is more appropriate for
malloc