Are C++ Containers exception-safe?

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.

Upvotes: 1

Views: 1000

Answers (3)

Loki Astari
Loki Astari

Reputation: 264331

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:

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:
— if an exception is thrown by an insert() function while inserting a single element, that function has no effects.
— if an exception is thrown by a push_back() or push_front() function, that function has no effects.
— no erase(), clear(), pop_back() or pop_front() function throws an exception.
— no copy constructor or assignment operator of a returned iterator throws an exception.
— no swap() function throws an exception.

Upvotes: 10

iammilind
iammilind

Reputation: 69968

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.

If you are allocating as an automatic variable then they are exception safe.

Upvotes: 0

Nicol Bolas
Nicol Bolas

Reputation: 473222

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.

Upvotes: 1

Related Questions