文档目录

一、为什么移动构造函数要加 noexcept?

struct Widget {
    Widget(Widget&& other) noexcept { /* 移动资源 */ }
    Widget& operator=(Widget&& other) noexcept { /* ... */ }
};

原因:std::vector 扩容时,如果移动构造是 noexcept,它用 移动 搬移旧元素到新内存。如果不是 noexcept,它只能用 拷贝(因为拷贝抛异常时旧数组还在,移动抛异常时旧数组已被破坏)。

std::vector<Widget> v;
v.push_back(Widget{});  // 可能触发扩容

// 如果 Widget 的移动构造是 noexcept:
//   → 把旧元素 move 到新内存(指针交换,快)
// 如果 Widget 的移动构造不是 noexcept:
//   → 把旧元素 copy 到新内存(深拷贝,慢)