c – 为什么cppcheck说“函数参数应该通过引用传递”?
发布时间:2020-12-16 09:50:04 所属栏目:百科 来源:网络整理
导读:这是cppcheck show waring的代码“[event.cpp:20] :(性能)函数参数’path’应该通过引用传递.” voidevent::set_path(const std::string path){ this-_path = path;} 但其他代码包括字符串paramer不显示此警告,如: intwatcher::init_watch(const struct st
这是cppcheck show waring的代码“[event.cpp:20] :(性能)函数参数’path’应该通过引用传递.”
void event::set_path(const std::string path) { this->_path = path; } 但其他代码包括字符串paramer不显示此警告,如: int watcher::init_watch(const struct stat *sb,std::string path,bool linked) { int wd; .... } 为什么? 解决方法
因为它应该!没有理由传递const副本,无论如何都无法修改它,所以为什么要复制它.在最坏的情况下,它必须为一个全新的字符串分配内存,然后一次一个字节地复制字符串.在最好的情况下,它可能会执行一些内部引用计数魔术,但如果您只是通过引用传递它,那么您最多只能复制一个指向堆栈中新点的指针.传递const std :: string&路径 – 它会快得多.
init_watch中的path参数也应该通过const引用传入,因为它也会无缘无故地创建一个副本. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |