如果这个问题还很不完整,不清楚或重复(这是我在这里的第一个问题),请提前抱歉。在研究移动语义并为OOP课程设计一个小项目时,我偶然发现了一个我自己无法回答的问题。据我所知,std :: move()通过将l值转换为r值来工作,但让我们假设我们将一个包含很多元素的向量移动到容量为1的第二向量中。我可以使用reserve( )以避免对第二个向量进行大量的自动内存重新分配,或者由于std :: move()将r值移动到第二个向量中而使用reserve()无效吗?我的问题的简单实现可以在下面找到。
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> first (1000000);
std::vector<int> second (1);
std::fill(first.begin(),first.end(),7);
second.reserve(1000000);//is this needed??
second=std::move(first);
return 0;
}
Run Code Online (Sandbox Code Playgroud)