问题描述
请考虑以下内容:
std::vector<std::unique_ptr<int>> ptrsToInts;
ptrsToInts.emplace_back(new int);
如果向量中发生了重新分配,但失败了(抛出std::bad_alloc
),我是安全的"还是泄漏int
?
If reallocation occurs in the vector, and that fails (throwing std::bad_alloc
), am I "safe" or will I leak an int
?
C ++ 11 23.3.6.5 [vector.modifiers]/1说:
C++11 23.3.6.5 [vector.modifiers]/1 says:
似乎表明这是一个潜在问题.也就是说,如果没有效果",那么就不会构造unique_ptr
,因此析构函数的行为将依赖于delete
不会发生指针. (这可能表明emplace_back
的容器应禁止使用emplace_back
)
which seems to indicate that this is a potential problem. That is, if there are "no effects", then no unique_ptr
ever was constructed, and therefore the destructor behavior one would rely on to delete
that pointer would not occur. (Which might indicate that emplace_back
should be banned for containers of unique_ptr
s)
推荐答案
如果需要重新分配并且失败,那么是的,您的对象永远不会进入容器,因此会丢失.
If reallocation is required and it fails, then yes, your object never went into the container and will thus be lost.
但是,应注意,这是纯用户错误.对于unique_ptr
的容器,不应禁止" emplace_back
,因为这样做有非常安全的方式(例如,事先reserve
留出空间,因此您知道它将一直存在).另外,您可以传入整个unique_ptr
,因为它完全可以使用move构造函数.
However, it should be noted that this is pure user error. emplace_back
should not be "banned" for containers of unique_ptr
, because there are perfectly safe ways of doing this (such as reserve
ing the space beforehand, so you know it will always be there). Also, you can pass in whole unique_ptr
s, since it's perfectly capable of using a move constructor.
所以,确实,在抛出异常之前,没有正确地将非RAII对象(int*
)包装在RAII对象中是您的错.
So really, it's your fault for not properly wrapping your non-RAII object (the int*
) in a RAII object before the point where you could throw exceptions.
这篇关于将emplace_back与unique_ptrs容器一起使用是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!