Łuk*_*Lew 3 c++ move-semantics c++11
我们假设T是可移动的对象:
vector<T> v;
v.resize(...)
Run Code Online (Sandbox Code Playgroud)
如果需要重新分配,那么该代码是否会调用副本,或者在所有元素上移动构造函数?
如果答案是"移动构造函数",那么编译器如何知道它应该使用这个?
#include <vector>
#include<memory>
int main() {
std::vector<std::unique_ptr<int>> v;
for(int i = 0; i < 1000; ++i) {
v.push_back(std::unique_ptr<int>(new int));
}
}
Run Code Online (Sandbox Code Playgroud)
如果std::vector使用了复制构造函数,则不会编译此代码.
如果答案是"移动构造函数",那么编译器如何知道它应该使用这个?
std::vector 可以用 std::move
如果它使用std::move但没有移动构造函数,它将等同于仅使用复制构造函数