Ins*_*oop 8 c++ move vector c++11
我一直在使用std :: vector来理解何时构造,破坏,复制构造和移动构造的对象.为此,我编写了以下程序
#include <iostream>
#include <vector>
class Test {
public:
Test() {
std::cout << "Constructor called for " << this << std::endl;
}
Test(const Test& x) {
std::cout << "Copy Constructor called for " << this << std::endl;
}
Test(Test&& x) {
std::cout << "Move Constructor called for " << this << std::endl;
}
~Test() {
std::cout << "Destructor called for " << this << std::endl;
}
};
int main() {
std::vector<Test> a( 1 );
a.resize(3);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
调整大小时,会重新分配.我的猜测是将对象a [0]移动构造为新的a [0].但是,使用libc ++和libstdc ++,似乎调用了复制构造函数而不是移动构造函数.这种行为有什么理由吗?
Ins*_*oop 13
我刚刚找到了问题的答案.移动构造函数必须声明为noexcept才能这样做.当这样的改变已经完成
Test(Test&& x) noexcept {
std::cout << "Move Constructor called for " << this << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
调用move构造函数.