为什么CPPCHECK说"Function parameter should be passed by reference"?
why cppcheck say "Function parameter should be passed by reference"?
这是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参考传递,因为这也将无缘无故地制作副本。
相关文章:
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 将 std::thread by 值推送到列表中
- MATLAB to C++: csvread() not supported by MATLAB Coder
- Makefile by ocaml 和 cpp 扩展名
- C++ OpenCV Randu 函数抛出'Integer division by zero'
- 从函数 BY VALUE 返回数组,返回结构时会发生什么?
- 如何在不受其他文件影响的情况下"by itself" Visual Studio 项目中运行C++文件?
- MacPorts:"Error: clang-4.0 has been replaced by clang-8.0; please install that instead",但我已经安装了clang
- 为什么 c++ 向量没有"delete by index"?
- 这个给定的代码应该将给定的数字转换为尽可能滞后的数字,no.by 用 9.It 替换合适的数字是行不通的
- 传递类 by-value 时,调用方或被调用方是否调用析构函数
- By-ref 参数:这是 std::thread 和 std::bind 之间的不一致吗?
- 转到特定页面后,如何将滑动视图的当前索引设置为选项卡栏"by reference"的当前索引?
- base64 decode with openssl BIO block by block
- 如何在 C++ 中修复"/usr/bin/ld: warning: liblber-2.4.so.2, needed by //usr/lib/x86_64-linux-gnu/libcurl-gnu
- 由mpglib输出的"hip: Can't rewind stream by 74 bits"到底意味着什么?
- 用rvalue参考和变异模板bits bits bys blamda by
- "All arguments to functions are passed by value" C 中的,C++ 中对引用传递的混淆
- 为什么CPPCHECK说"Function parameter should be passed by reference"?
- C++:参数传递"passed by reference"