为什么需要将移动构造函数和移动赋值运算符标记为noexcept
#include <iostream>
#include <vector>
using namespace std;
class A1 {
public:
A1() { cout << "ctor" << endl; }
A1(const A1 &other) { cout << "cp-ctor" << endl; }
A1& operator=(const A1 &other) { cout << "cp-eqop" << endl; return *this; }
A1(A1 &&other) noexcept { cout << "mv-ctor" << endl; } // noexcept is necessary!
A1& operator=(A1 &&other) noexcept { cout << "mv-eqop" << endl; return *this; }
int num = 100;
};
int main() {
vector<A1> arr;
A1 a1;
cout << "---- test push_back ----" << endl;
arr.push_back(a1);
cout << "---- test emplace_back ----" << endl;
arr.emplace_back(a1);
}
// output:
// ctor
// ---- test push_back ----
// cp-ctor
// ---- test emplace_back ----
// cp-ctor
// mv-ctor