如果在将对象移动到 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? */
如果在将对象移动到 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? */
这在[container.requirements.general]/11.2中有介绍
push_back()如果,push_front(),emplace_back(), 或函数抛出异常emplace_front(),则该函数无效。
因此,如果发生异常,您将不会从对象移动。
这仅涵盖向量是否抛出。我们需要查看[vector.modifiers]/1来看看如果移动构造函数本身抛出了会发生什么:
如果在末尾插入单个元素时抛出异常并且
T是Cpp17CopyInsertable或is_nothrow_move_constructible_v<T>istrue,则没有效果。否则,如果非Cpp17CopyInsertableT的移动构造函数引发异常,则未指定效果。
强调我的
在这种情况下,行为是未指定的。
在您的情况下std::string,有一个noexcpet移动构造函数,因此如果抛出异常,您将拥有一个有效的对象。