std::vector 作为参数传入,是值传递,vector本身,及vector内的所有元素都会复制一遍。
得不偿失,可以使用引用传递。
std::vector作为函数返回值,是不会创建新vector对象的。函数内返回的跟接收返回值的是一个对象。
读取vector内的元素,如果赋值给其他变量,是将对象复制一份新的。
Item ii = list[0];
如果直接操作数组元素,是不会产生对象复制的
list[0].a
#include <stdlib.h>
#include <stdio.h>
#include <vector>
class Item{
public:
int a;
int b;
};
std::vector<Item> vectorTestFunc(std::vector<Item> input){
printf("vectorTestFunc >>> in %p %p, %p\n",&input, &input[0], &input[0].a);
Item item = input[0];
std::vector<Item> output;
output.push_back(item);
printf("vectorTestFunc <<< in %p %p, %p\n",&output, &output[0], &output[0].a);
return output;
}
int main(int argc, char* argv[]){
std::vector<Item> list;
Item i;
i.a = 1;
i.b =2;
printf("i adr is %p, %p\n",&i, &i.a);
list.push_back(i);
printf("list[0] adr is %p, %p\n",&list[0], &list[0].a);
Item ii = list[0];
printf(" ii adr is %p, %p\n",&ii, &ii.a);
printf("vectorTestFunc in %p %p, %p\n",&list, &list[0], &list[0].a);
std::vector<Item> output = vectorTestFunc(list);
printf("vectorTestFunc output %p %p, %p\n",&output, &output[0], &output[0].a);
return 0;
}
build$ make; ./main
Scanning dependencies of target main
[ 50%] Building CXX object CMakeFiles/main.dir/main.cpp.o
[100%] Linking CXX executable main
[100%] Built target main
i adr is 0x7ffc5a16b160, 0x7ffc5a16b160
list[0] adr is 0x5583c3b0f280, 0x5583c3b0f280
ii adr is 0x7ffc5a16b168, 0x7ffc5a16b168
vectorTestFunc in 0x7ffc5a16b170 0x5583c3b0f280, 0x5583c3b0f280
vectorTestFunc >>> in 0x7ffc5a16b1b0 0x5583c3b0f2a0, 0x5583c3b0f2a0
vectorTestFunc <<< in 0x7ffc5a16b190 0x5583c3b0f2c0, 0x5583c3b0f2c0
vectorTestFunc output 0x7ffc5a16b190 0x5583c3b0f2c0, 0x5583c3b0f2c0
如果把函数参数改成引用:
build$ make; ./main
Scanning dependencies of target main
[ 50%] Building CXX object CMakeFiles/main.dir/main.cpp.o
[100%] Linking CXX executable main
[100%] Built target main
i adr is 0x7ffe81b1cf40, 0x7ffe81b1cf40
list[0] adr is 0x5641c6771280, 0x5641c6771280
ii adr is 0x7ffe81b1cf48, 0x7ffe81b1cf48
vectorTestFunc in 0x7ffe81b1cf50 0x5641c6771280, 0x5641c6771280
vectorTestFunc >>> in 0x7ffe81b1cf50 0x5641c6771280, 0x5641c6771280
vectorTestFunc <<< in 0x7ffe81b1cf70 0x5641c67712a0, 0x5641c67712a0
vectorTestFunc output 0x7ffe81b1cf70 0x5641c67712a0, 0x5641c67712a0
以上代码在 gcc version 7.3.0 (Ubuntu 7.3.0-16ubuntu3)上测试