Software_t
Software_t

Reputation: 586

const TYPE& - when I will want to use by reference to const?

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

Answers (1)

Garrett Gutierrez
Garrett Gutierrez

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

Related Questions