是 C++容器异常安全?
我使用隐式构造函数和一个输入属性的 load()
成员,但也可以抛出异常。
我的问题是:如果属性是日常 C++ 容器,如果 load()
中发生异常,我是否会出现内存泄漏?
感谢您的阅读。
编辑:示例代码有助于澄清我的问题。
class One
{
public:
std::vector<int> stuff;
void load() {
stuff.resize(13);
stuff[0] = 43;
std::bad_alloc ba;
throw ba; // will this cause memory leaks? (as far as this class is concerned)
}
}
我知道这是一个愚蠢的问题,但我不得不问。
I use the implicit Constructor and a load()
Member which inputs the Attributes, but can also throw exceptions.
My question is: if the Attributes are everyday C++ Containers will I get memory leaks if exceptions happen in load()
?
Thank you for reading.
Edit: example code to help clarify my question.
class One
{
public:
std::vector<int> stuff;
void load() {
stuff.resize(13);
stuff[0] = 43;
std::bad_alloc ba;
throw ba; // will this cause memory leaks? (as far as this class is concerned)
}
}
I know this is a silly question but I had to ask it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
容器本身是异常安全的。
但这也取决于放置在容器中的类型以及是否正确编写。
即:异常不应逃逸析构函数
该标准定义了对容器和异常的以下保证:
23.2.1 一般容器要求 [container.requirements.general]
第 10 段:
The container itself is exception safe.
But it also depends on the type being placed in the contain and if it has been written correctly.
i.e.: Exceptions should not escape the destructor
The standard defines the following guarantees on containers and exceptions:
23.2.1 General container requirements [container.requirements.general]
Paragraph 10:
是的,容器是异常安全的。只要你不做一些恶作剧,比如在堆上分配它们(没有异常安全的智能指针)或类似的事情,你就会没事的。
Yes, containers are exception safe. As long as you aren't doing shenanigans like allocating them on the heap (without exception-safe smart pointers) or such like that, you'll be fine.
由于你的问题没有说明太多,这是我的看法。
如果您使用
new/new[]
(在load()
内部)分配内存,那么您必须使用delete/delete[]
取消分配,当抛出异常时。如果您作为自动变量进行分配,那么它们是异常安全的。
Since your question doesn't state much, here is my take.
If you are allocating memory using
new/new[]
(inside yourload()
) then you have to deallocate usingdelete/delete[]
, when exception is thrown.If you are allocating as an automatic variable then they are exception safe.