pass by reference
- 对于数组和结构这种大的数据,按值传递(pass by value)需要创建副本,占内存费时间,使用引用就只传地址,和按指针传递一样,但是使用起来又比指针简单安全,就是在使用原数据。
- 对于unique_ptr智能指针模板类,它只允许源指针是临时右值时候的赋值,所以如果实参不是临时右值,按值传递就会成为非法赋值,编译器报错。示例:
#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include <algorithm> //for_each函数
using std::string;
using std::cout;
using std::cin;
using std::endl;
std::unique_ptr<int> make_int(int n)
{
return std::unique_ptr<int> (new int(n));//返回int的智能指针,用传入的参数n初始化
}
void show(std::unique_ptr<int> & a)//这里必须按引用传递,因为如果按值传递
//那么就要用一个非临时右值作为a的实参,对于unique_ptr类是不允许的
{
cout << *a << ' ';
}
int main()
{
int size = 5;
std::vector<std::unique_ptr<int>> vp(size);
for (int i=0;i<size;++i)
vp[i] = make_int(rand() % 1000);
vp.push_back(make_int(rand() % 1000));//可以调用成功是因为参数是一个临时右值
for_each(vp.begin(), vp.end(), show);
return 0;
}
41 467 334 500 169 724
Process returned 0 (0x0) execution time : 0.329 s
Press any key to continue.