给定一个类型为std::vector<std::unique_ptr<SomeType> >
的向量,是否可以在其上使用remove_if
函数?换句话说,考虑以下代码:
std::vector<std::unique_ptr<SomeType> > v;
// fill v, all entries point to a valid instance of SomeType...
v.erase( std::remove_if( v.begin(), v.end(), someCondition ), v.end() );
在使用 erase 后,在 vector v
中的所有指针是否仍然有效?我知道根据std::remove_if
的直观实现以及我查看过的所有实现,它们将是有效的。但我想知道标准中是否有任何保证;即 std::remove_if
不允许复制任何有效条目,而是需要将复制重新复制到其最终位置。
(当然,我假设条件不会复制。如果条件具有类似以下签名的形式:
struct Condition
{
bool operator()( std::unique_ptr<SomeType> ptr ) const;
};
当使用remove_if
函数时,如果该容器使用指针指向其元素,那么在执行remove_if
后所有指针都将无效。
unique_ptr
不能进行拷贝构造,因此如果你使用了该谓词,你的代码将无法编译通过。 - interjaystd::unique
是可移动但不可复制的。它可以被移动到容器的末尾。 - ali_bahooauto_ptr
中是正确的,但在unique_ptr
中不是(代码根本无法编译)。 - interjay