现在就讨论一下,把vector作为函数的参数进行传递。
也是直接上一段代码:
#include<iostream> #include<vector> #include <memory> using namespace std; void display_vector(vector<unique_ptr<int>> vec); int main() { vector<unique_ptr<int>> vec; unique_ptr<int> s1(new int(1)); unique_ptr<int> s2(new int(2)); unique_ptr<int> s3(new int(3)); unique_ptr<int> s4(new int(4)); vec.push_back(std::move(s1)); vec.push_back(std::move(s2)); vec.push_back(std::move(s3)); vec.push_back(std::move(s4)); display_vector(vec);//还是所有权的问题 return 0; } void display_vector(vector<unique_ptr<int>> vec) { for (auto it = vec.begin(); it != vec.end(); it++) { cout << **it << endl; } }
这个时候给display_vector传递std::move(vec)作为参数,并看一下调用display_vector函数后,vec变成了什么呢?
#include<iostream> #include<vector> #include <memory> using namespace std; void display_vector(vector<unique_ptr<int>> vec); int main() { vector<unique_ptr<int>> vec; unique_ptr<int> s1(new int(1)); unique_ptr<int> s2(new int(2)); unique_ptr<int> s3(new int(3)); unique_ptr<int> s4(new int(4)); vec.push_back(std::move(s1)); vec.push_back(std::move(s2)); vec.push_back(std::move(s3)); vec.push_back(std::move(s4)); display_vector(std::move(vec)); cout << "now, vec size:" << vec.size() << endl; return 0; } void display_vector(vector<unique_ptr<int>> vec) { for (auto it = vec.begin(); it != vec.end(); it++) { cout << **it << endl; } } //输出: 1 2 3 4 now, vec size:0
传统的想法,我们传递的是值,而非引用,那为什么会影响vec呢,还是所有权转移问题。
那么我们如何不改变vec呢?
只要按引用、或是const引用传递即可,就不涉及到所有权的转移问题:
#include<iostream> #include<vector> #include <memory> using namespace std; void display_vector(vector<unique_ptr<int>> &vec); int main() { vector<unique_ptr<int>> vec; unique_ptr<int> s1(new int(1)); unique_ptr<int> s2(new int(2)); unique_ptr<int> s3(new int(3)); unique_ptr<int> s4(new int(4)); vec.push_back(std::move(s1)); vec.push_back(std::move(s2)); vec.push_back(std::move(s3)); vec.push_back(std::move(s4)); display_vector(vec); cout << "now, vec size:" << vec.size() << endl; return 0; } void display_vector(vector<unique_ptr<int>> &vec) { for (auto it = vec.begin(); it != vec.end(); it++) { cout << **it << endl; } } //输出: 1 2 3 4 now, vec size:4