为什么CPPCHECK说"Function parameter should be passed by reference"?

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

本文关键字:by passed reference be parameter CPPCHECK Function 为什么 should      更新时间:2023-10-16

这是cppcheck show警告的代码" [event.cpp:20] :(性能)函数参数'路径'应该通过参考传递。"

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

但是其他代码(包括字符串参数)不显示此警告,例如:

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

为什么?

,因为它应该!没有理由传递const副本,您无论如何都无法修改它,所以为什么要复制它。在最坏的情况下,它将必须为一个全新的字符串分配内存,然后一次复制一个字节。在最好的情况下,它可能会执行一些内部参考计数魔术,但是如果您只是通过参考将其传递,那么您最多可以将单个指针复制到堆栈中的新点。通过const std::string& path通过 -

会更快。

init_watch中的路径参数也应通过const参考传递,因为这也将无缘无故地制作副本。

相关文章: