#include <string>
#include <iostream>
#include <memory>
using namespace std;
pair<int *,int *> ptr()
{
//这两个数组都定义成static的就可以了
int p1[3]={123,2,3};
int p2[3]={1234,1,2};
return make_pair(p1,p2);
}
int main()
{
pair<int*,int*> p = ptr();
int *p1 = p.first;
int *p2 = p.second;
for(int i = 0; i != 3; ++i)
cout << p1[i] << endl;
for(int j = 0; j != 3; ++j)
cout << p2[j] << endl;
return 0;
}
运行结果是:
123
22033
-588110800
22033
1703825584
32765
后来发现,如果把函数ptr中的两个数组都定义称为static就没事了,因为这两个数组p1和p2都是局部临时量,当函数运行完毕后,返回p1和p2的pair,但是p1、p2所指向的数组早就被销毁了。所以打印出来的值早就不存在了。这就是为何不能返回临时量。
#include <string>
#include <