假设 T
是可 move 的对象:
vector<T> v;
v.resize(...)
如果需要重新分配,那么该代码会在所有元素上调用复制或 move 构造函数吗?
如果答案是“move 构造函数”,那么编译器如何知道它应该使用这个构造函数?
最佳答案
#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));
}
}
如果 std::vector
使用复制构造函数,则不会编译此代码。
If the answer is "move constructor" then how does the compiler know that it should use this one?
std::vector
可以使用 std::move
如果它使用 std::move
但没有 move 构造函数,它将等同于只使用复制构造函数
关于c++ - 可 move 元素的 vector 会有效地调整大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17010269/