简体   繁体   English

std::vector 不是异常安全的?

[英]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.我听说过几次提到std::vector在存储原始指针时不是异常安全的,应该使用unique_ptrshared_ptr代替。

My question is, why is std::vector not exception-safe and how do these classes fix that?我的问题是,为什么std::vector不是异常安全的,这些类如何解决这个问题?

It's not std::vector that's not exception safe, it's using raw pointers for memory management: std::vector不是异常安全的,它使用原始指针进行 memory 管理:

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.) (或者更昂贵的shared_ptr 。您也可以使用来自 Boost 的指针容器。)

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.通过“不是异常安全”,我认为他们的意思是如果向量在异常期间被展开破坏,将会发生 memory 泄漏。

Shared_ptr makes sure the objects pointed to by the pointers are deleted when the vector itself is destroyed. Shared_ptr 确保指针指向的对象在 vector 本身被销毁时被删除。

Another alternative is the Boost pointer containers .另一种选择是Boost 指针容器

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

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