【发布时间】:2015-11-05 05:33:16
【问题描述】:
请原谅我对这个话题不够清楚。我正在尝试创建用于将大类插入向量的函数。在这个例子中,我使用整数向量作为大类。
#include <vector>
#include <iostream>
using namespace std;
vector<vector<int>> vectorOfVectors;
void fn(const vector<int> &v) {
vectorOfVectors.push_back(v);
}
void fn(vector<int> &&v) {
vectorOfVectors.push_back(std::move(v));
}
int main() {
vector<int> a({1});
const vector<int> b({2});
fn(std::move(a));
fn(b);
cout<<b[0];
}
显然,我希望尽可能不进行复制。我的问题:
- 此代码是否正确?
- 有更好的方法吗?
- 对于使用自定义类的相同方法,是否需要定义移动构造函数?
【问题讨论】:
标签: c++ c++11 rvalue-reference