我注意到我通常使用常量引用作为返回值或参数.我认为原因是它与在代码中使用非引用几乎相同.但它肯定需要更多的空间和功能声明变得更长.我很喜欢这样的代码,但我认为有些人发现它编程风格很糟糕.
你怎么看?是否值得编写const int& over int?我认为无论如何它都是由编译器优化的,所以也许我只是在浪费时间编码,一个?
使用我的直觉,我认为新的 string_view 需要通过引用传递,因为这更有效(只传递指针而不是完整的类)。然而,一些消息来源表明最好按值传递它,避免“别名”问题。
在尝试几种替代方案时,我证实了我的直觉,如果该函数只是转发 string_view(所有源代码都用 编译/Ox),那么通过引用传递会更快
例如,这段代码
extern auto otherMethodByReference(const std::string_view &input) -> void;
auto thisMethodByReference(int value, const std::string_view &input) -> void
{
otherMethodByReference(input);
}
Run Code Online (Sandbox Code Playgroud)
导致了这个程序集
00000 48 8b ca mov rcx, rdx
00003 e9 00 00 00 00 jmp ?otherMethodByReference@@YAXAEBV?$basic_string_view@DU?$char_traits@D@std@@@std@@@Z ; otherMethodByReference
Run Code Online (Sandbox Code Playgroud)
虽然这段代码
extern auto otherMethodByValue(std::string_view input) -> void;
auto thisMethodByValue(int value, std::string_view input) -> void
{
otherMethodByValue(input);
}
Run Code Online (Sandbox Code Playgroud)
导致了这个程序集
00000 48 83 ec 38 sub rsp, 56 ; 00000038H
00004 0f …Run Code Online (Sandbox Code Playgroud) c++ parameter-passing compiler-optimization string-view visual-studio-2017
最近,在代码审查期间,我偶然发现了std::string_view通过引用传递的参数。例如下面的代码:
void fun(std::string_view a);
Run Code Online (Sandbox Code Playgroud)
变成
void fun(std::string_view& a);
Run Code Online (Sandbox Code Playgroud)
我觉得这很麻烦,原因如下:
l-value std::string_view。std::string_view是避免复制底层字符串,所以我认为使用&它没有意义。问题是,将std::string_view参数声明为按引用传递而不是按值传递是否有任何优点?