Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why cppcheck say "Function parameter should be passed by reference"?

Tags:

c++

cppcheck

This is the code of cppcheck show warning "[event.cpp:20]: (performance) Function parameter 'path' should be passed by reference."

void
event::set_path(const std::string path)
{
    this->_path = path;
}

but other code including string parameter dont show this warning, like:

int
watcher::init_watch(const struct stat *sb, std::string path, bool linked)
{
    int wd;
        ....
}

why?

like image 427
fayewu Avatar asked Jan 11 '23 09:01

fayewu


1 Answers

Because it should! There is no reason to pass a const copy, you can't modify it anyway, so why copy it. In the worst case it's going to have to allocate memory for a brand new string, then copy the string one byte at a time. In the best case it might do some internal reference counting magic, but if you just passed it by reference then you're at most copying a single pointer to the new point in the stack. pass by const std::string& path - It will be much faster.

The path parameter in init_watch should be passed in by const reference too, because that is going to make a copy too for no reason.

like image 81
Salgar Avatar answered Jan 25 '23 06:01

Salgar