In C I know how to pass a vector as pointer:
void my_func (vector<int>* arr)
But how can I implement:
Make the vector const, ie don't allow change of arr = ...
Make the values of the vector const, ie don't allow changes to the values of arr.
I read a lot of posts here but got too much confused about const meaning with complex DS like vector and others.
CodePudding user response:
Both of your desires can be satisfied by tagging the argument as const
:
void my_func(const vector<int> * arr)
... although unless you need to be able to pass a NULL-pointer for some reason, it's better to pass the array by-reference than by-pointer:
void my_func(const vector<int> & arr)
Note that you can have both (1) and (2), or neither, but not one-and-not-the-other. Modifying the member-values of the vector is considered modifying the vector, so tagging the vector as const
prohibits both types of modification.
CodePudding user response:
Basically the situation is
void do_something( std::vector<int>* ptr_to_vec) {
ptr_to_vec->push_back(42);
(*ptr_to_vec)[0] = 5;
}
void cannot_do_something(const std::vector<int>* ptr_to_vec) {
// both of the following will not compile
//ptr_to_vec->push_back(42);
//(*ptr_to_vec)[0] = 5;
}
CodePudding user response:
Rule of thumb: const
applies to the thing on its left, unless there is nothing there, then it applies to the thing on its right instead.
So...
Make the vector const, ie don't allow change of arr = ...
vector<int>* const arr
will apply const
to *
, ie arr
will be a const
pointer to a non-const vector
. arr
itself can't be changed to point at a different vector
object, but the vector
itself can have its members modified when accessed via arr
.
Make the values of the vector const, ie don't allow changes to the values of arr.
const vector<int>* arr
(or vector<int> const * arr
) will apply const
to vector
, ie arr
will be a non-const pointer to a const vector
object. The vector
's members can't be modified when accessed via arr
, but arr
itself can be changed to point at a different const vector
object.
And then, you can combine the two, if needed:
const vector<int>* const arr
(or vector<int> const * const arr
) will make arr
be a const
pointer to a const vector
object. Neither the pointer nor the vector
can be changed/modified.