将对象移入std :: vector时的异常保证

Uni*_*ant 1 c++ stdvector exception-safety

如果在将对象移至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? */
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 7

[container.requirements.general] /11.2中对此进行了介绍。

如果一个异常被抛出push_­back()push_­front()emplace_­back(),或emplace_­front()功能,该功能没有任何影响。

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

仅在向量抛出时覆盖。我们需要查看[vector.modifiers] / 1来查看如果move构造函数本身抛出的情况:

如果在在端部插入单个元件的抛出异常,并且TCpp17CopyInsertableis_­nothrow_­move_­constructible_­v<T>true,没有影响。否则,如果非Cpp17CopyInsertable 的move构造函数引发异常T,则效果未指定。

重点矿

在这种情况下,行为是不确定的。


在您的情况下,std::string有一个noexcpetmove构造函数,因此,如果引发异常,则将有一个有效的对象。