Reputation: 71
I know when you pass an array as a parameter, you basically pass the address of the array at index 0. Then, the hardware knows that int is usually 4 bytes, so it can easily access other elements. My question is about vector. If I have a function
void bla(std::vector<int> &arr)
{
}
Then it should pass a reference to the vector, but does it happen as with arrays? Vectors are implemented using arrays, so my assumption is that when I pass a reference, it simply passes the address of the first element. Is it correct or not?
Also, if I pass just as a vector, what will happen? Will it create a copy on stack? Thanks
Upvotes: 1
Views: 2469
Reputation: 13589
In general:
void foo(Bar b)
- pass by value, b
is a copy or the original Bar
.void foo(Bar& b)
- pass by reference, you can modify the original Bar
through b
.void foo(Bar* b)
- pass by pointer, you can modify the original Bar
through b
(as long as b
is not null).void foo(const Bar& b)
- pass by const reference, b
is the original Bar
but you cannot modify it in the scope of foo
.void foo(const Bar* b)
- pass by pointer-to-const, b
is a pointer to the original Bar
but you cannot modify it in the scope of foo
.void foo(Bar* const b)
- pass by const pointer, b
is a pointer to the original Bar
, and the original Bar
can be modified (as long as b
is not null), but you can't change what b
points to.void foo(const Bar* const b)
- pass by const pointer-to-const, you cannot change the original Bar
nor can you change what b
points to in the scope of foo
.Upvotes: 0
Reputation: 42924
std::vector
is very different than a raw C-style array, so if you pass a std::vector
by reference nobody can say that the address of the first item in the std::vector
is what is passed to the function.
Inside the std::vector
there is more logic than just "raw C-style array".
If you want the address of the first item in the vector, you can get it using &v[0]
or v.data()
.
If you pass a vector by value you get a copy of the original vector. And all the modifications you do to that copy inside your function are not reflected to the original.
Upvotes: 5
Reputation: 185
If you pass a vector by reference, the entire array is passed and can be edited. It does not pass the address of the first element. Otherwise, if you don't pass by reference, it only makes a copy of the array.
Source: School coding experience (please edit if this is inaccurate).
Upvotes: 0