Are vectors passed to functions by value or by reference in C++

前端 未结 4 1422
时光取名叫无心
时光取名叫无心 2020-12-04 06:15

I\'m coding in C++. If I have some function void foo(vector test) and I call it in my program, will the vector be passed by value or reference? I\'m

4条回答
  •  无人及你
    2020-12-04 06:40

    A vector is functionally same as an array. But, to the language vector is a type, and int is also a type. To a function argument, an array of any type (including vector[]) is treated as pointer. A vector is not same as int[] (to the compiler). vector is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor.

    So, you must use vector& (preferably with const, if function isn't modifying it) to pass it as a reference.

提交回复
热议问题