blog icon indicating copy to clipboard operation
blog copied to clipboard

C++ constant reference: const&

Open qingquan-li opened this issue 2 years ago • 0 comments

#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:

  • https://releases.llvm.org/6.0.0/tools/clang/tools/extra/docs/clang-tidy/checks/performance-unnecessary-value-param.html
  • https://stackoverflow.com/questions/1943276/what-does-do-in-a-c-declaration
#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;
}

qingquan-li avatar Jun 18 '22 15:06 qingquan-li