SirGuy
SirGuy

Reputation: 10780

std::vector not exception-safe?

I've heard it mentioned a couple of times that std::vector is not exception-safe when storing raw pointers and that one should use unique_ptr or shared_ptr instead.

My question is, why is std::vector not exception-safe and how do these classes fix that?

Upvotes: 1

Views: 2458

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308392

By "not exception safe" I presume they mean there will be a memory leak if the vector is destroyed by the unwinding during an exception.

Shared_ptr makes sure the objects pointed to by the pointers are deleted when the vector itself is destroyed.

Another alternative is the Boost pointer containers.

Upvotes: 2

GManNickG
GManNickG

Reputation: 504063

It's not std::vector that's not exception safe, it's using raw pointers for memory management:

int main()
{
    try
    {
        int* i = new int;

        throw "oops, memory leak!";
    }
    catch (...){}
}

That has nothing to do with vector's per se, it's just that doing this is the exact same problem:

int main()
{
    try
    {
        std::vector<int*> vi;
        vi.push_back(new int);

        throw "oops, memory leak!";
    }
    catch (...){}
}

Both of these are fixed by using smart pointers:

int main()
{
    try
    {
        std::unique_ptr<int> i(new int);

        std::vector<std::unique_ptr<int>> vi;
        vi.push_back(std::unique_ptr<int>(new int));
        vi.push_back(std::move(i));

        throw "vector destroys unique_ptr's...which delete their memory";
    }
    catch (...){}
}

(Or shared_ptr, which is more expensive. You may also use pointer containers, from Boost.)

Upvotes: 5

Related Questions