gpt4 book ai didi

c++ - 为什么 cppcheck 说 "Function parameter should be passed by reference"?

转载 作者:太空狗 更新时间:2023-10-29 20:13:28 25 4
gpt4 key购买 nike

这是 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;
}

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

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

为什么?

最佳答案

因为它应该!没理由传一个const拷贝,反正修改不了,何必拷贝。在最坏的情况下,它将不得不为一个全新的字符串分配内存,然后一次一个字节地复制该字符串。在最好的情况下,它可能会做一些内部引用计数魔术,但如果您只是通过引用传递它,那么您最多只是将一个指针复制到堆栈中的新点。通过 const std::string& path - 它会快得多。

init_watch 中的路径参数也应该通过 const 引用传递,因为那也会无缘无故地制作拷贝。

关于c++ - 为什么 cppcheck 说 "Function parameter should be passed by reference"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21305132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com