現在就討論一下,把vector作為函數的參數進行傳遞。
也是直接上一段代碼:
#include
#include
#include
using namespace std;
void display_vector(vector> vec);
int main()
{
vector> vec;
unique_ptr s1(new int(1));
unique_ptr s2(new int(2));
unique_ptr s3(new int(3));
unique_ptr 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> vec)
{
for (auto it = vec.begin(); it != vec.end(); it++)
{
cout << **it << endl;
}
}
這個時候給display_vector傳遞std::move(vec)作為參數,並看一下調用display_vector函數後,vec變成了什麼呢?
#include
#include
#include
using namespace std;
void display_vector(vector> vec);
int main()
{
vector> vec;
unique_ptr s1(new int(1));
unique_ptr s2(new int(2));
unique_ptr s3(new int(3));
unique_ptr 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> 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
#include
#include
using namespace std;
void display_vector(vector> &vec);
int main()
{
vector> vec;
unique_ptr s1(new int(1));
unique_ptr s2(new int(2));
unique_ptr s3(new int(3));
unique_ptr 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> &vec)
{
for (auto it = vec.begin(); it != vec.end(); it++)
{
cout << **it << endl;
}
}
//輸出:
1
2
3
4
now, vec size:4