简体   繁体   English

C++ 容器是否是异常安全的?

[英]Are C++ Containers exception-safe?

I use the implicit Constructor and a load() Member which inputs the Attributes, but can also throw exceptions.我使用隐式构造函数和一个load()成员来输入属性,但也可以抛出异常。

My question is: if the Attributes are everyday C++ Containers will I get memory leaks if exceptions happen in load() ?我的问题是:如果属性是每天的 C++ 容器,如果load()中发生异常,我会得到 memory 泄漏吗?

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.我知道这是一个愚蠢的问题,但我不得不问。

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.但这也取决于放置在包含中的类型以及是否正确编写。

ie: 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] 23.2.1 一般容器要求 [container.requirements.general]

Paragraph 10:第 10 段:

Unless otherwise specified (see 23.2.4.1, 23.2.5.1, 23.3.3.4, and 23.3.6.5) all container types defined in this Clause meet the following additional requirements:除非另有规定(见 23.2.4.1、23.2.5.1、23.3.3.4 和 23.3.6.5),本条款中定义的所有容器类型均满足以下附加要求:
— if an exception is thrown by an insert() function while inserting a single element, that function has no effects. — 如果在插入单个元素时 insert() function 抛出异常,则 function 无效。
— if an exception is thrown by a push_back() or push_front() function, that function has no effects. — 如果 push_back() 或 push_front() function 抛出异常,则 function 无效。
— no erase(), clear(), pop_back() or pop_front() function throws an exception. — 没有 erase()、clear()、pop_back() 或 pop_front() function 会抛出异常。
— no copy constructor or assignment operator of a returned iterator throws an exception. — 返回的迭代器的任何复制构造函数或赋值运算符都不会引发异常。
— no swap() function throws an exception. — no swap() function 抛出异常。

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.只要您不进行诸如在堆上分配它们(没有异常安全的智能指针)之类的恶作剧,就可以了。

Since your question doesn't state much, here is my take.由于您的问题并不多,因此这是我的看法。

If you are allocating memory using new/new[] (inside your load() ) then you have to deallocate using delete/delete[] , when exception is thrown.如果您使用new/new[] (在您的load()内部)分配 memory ,那么当抛出异常时,您必须使用delete/delete[]解除分配。

If you are allocating as an automatic variable then they are exception safe.如果您将其分配为自动变量,那么它们是异常安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM