std::vector::operator=()的异常保证级别及分配失败时的状态与输出
std::vector::operator=() 的异常保证与相关问题解答
异常保证级别
std::vector::operator=() 具备强异常保证。强异常保证的核心逻辑是:如果赋值操作过程中抛出任何异常,被赋值的目标容器状态会完全回滚到操作执行前的状态,就像该赋值从未发生过一样。
抛出std::bad_alloc时原vector的状态
当赋值过程中因内存分配失败抛出std::bad_alloc,C++标准明确保证原vector处于有效且未被修改的状态。不会出现部分赋值、容器状态混乱的情况。
基本与强异常保证的区别
- 基本异常保证:仅保证抛出异常后对象处于有效状态,但对象的具体内容可能已被部分修改。
- 强异常保证:既保证对象有效,还保证对象状态完全回到操作执行前的初始状态,无任何修改痕迹。
std::vector::operator=()完全符合强异常保证的定义。
无法复制时的示例程序输出
假设示例代码如下:
#include <iostream> #include <vector> #include <stdexcept> int main() { std::vector<int> a = {1, 2, 3}; std::vector<int> b = {4, 5, 6, 7}; try { // 模拟内存分配失败导致复制失败 a = b; } catch (const std::bad_alloc& e) { std::cout << "Allocation failed: " << e.what() << '\n'; } for (int num : a) { std::cout << num << ' '; } std::cout << '\n'; return 0; }
当复制失败抛出std::bad_alloc时,程序会先输出异常信息(例如Allocation failed: std::bad_alloc),随后输出1 2 3——因为a的状态未被任何修改。
内容的提问来源于stack exchange,提问作者Andreev Gregory
相关产品推荐
相关产品推荐

