4

这是 cppcheck show warning "[event.cpp:20]: (performance) Function parameter 'path' should be pass 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;
        ....
}

为什么?

4

1 回答 1

9

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

路径参数 ininit_watch也应该通过 const 引用传递,因为这也会无缘无故地进行复制。

于 2014-01-23T10:18:02.313 回答