Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

C++ constant reference: const& #194

Open Qingquan-Li opened 2 years ago

Qingquan-Li commented 2 years ago
#include <iostream>
#include <string>

using namespace std;

void greeting(string);

int main() {
    greeting("Jake");
    return 0;
}

void greeting(string name) {
    cout << "Hi, " << name << endl;
}

CLion warning:

Clang-Tidy: The parameter 'name' is copied for each invocation but only used as a const reference; consider making it a const reference

How to Fix:

#include <iostream>
#include <string>

using namespace std;

void greeting(string const&);

int main() {
    greeting("Jake");
    return 0;
}

void greeting(string const& name) {
    cout << "Hi, " << name << endl;
}