1

如果在将对象移动到 std::vector 时内存分配失败,并且抛出 bad_alloc,std::vector 是否保证从对象移动的对象不变/仍然有效?

例如:

std::string str = "Hello, World!";
std::vector<std::string> vec;

vec.emplace_back(std::move(str));
/* Is str still valid and unaltered if the previous line throws? */
4

1 回答 1

7

这在[container.requirements.general]/11.2中有介绍

push_­back()如果, push_­front(), emplace_­back(), 或函数抛出异常emplace_­front(),则该函数无效。

因此,如果发生异常,您将不会从对象移动。

这仅涵盖向量是否抛出。我们需要查看[vector.modifiers]/1来看看如果移动构造函数本身抛出了会发生什么:

如果在末尾插入单个元素时抛出异常并且TCpp17CopyInsertableis_­nothrow_­move_­constructible_­v<T>is true,则没有效果。否则,如果非Cpp17CopyInsertable T的移动构造函数引发异常,则未指定效果。

强调我的

在这种情况下,行为是未指定的。


在您的情况下std::string,有一个noexcpet移动构造函数,因此如果抛出异常,您将拥有一个有效的对象。

于 2019-08-09T18:35:02.333 回答