Reputation: 586
I read about reference variable
in cpp, and I don't understand when I will want to use with reference to const? for what it's good?
Upvotes: 0
Views: 167
Reputation: 767
Use a reference when you either don't want to copy the parameter or want to alter the original rather than a copy local to the scope of the function.
Use const when you do want the parameter to be constant during the duration of the function.
So then use a const reference when you both do not want to copy the parameter but do not want to alter it.
For example:
void print_vector(const std::vector<std::string>& strvector) {
for (unsigned int i = 0; i < strvector.size(); i++) {
std::cout << strvector[i] << std::endl;
}
}
This method only cout
's every string in a vector. It would be wasteful to copy the entire vector, thus the &
. But you don't want to alter the vector passed as a parameter either, thus the const
.
Upvotes: 1