我听取了香草萨特最近的谈话谁建议的理由来传递std::vector和std::string利用const &在很大程度上消失了.他建议现在更好地编写如下函数:
std::string do_something ( std::string inval )
{
std::string return_val;
// ... do stuff ...
return return_val;
}
Run Code Online (Sandbox Code Playgroud)
我理解return_val在函数返回时将是一个rvalue,因此可以使用非常便宜的移动语义返回.但是,inval仍然远大于引用的大小(通常实现为指针).这是因为a std::string具有各种组件,包括指向堆的指针和char[]用于短字符串优化的成员.所以在我看来,通过引用传递仍然是一个好主意.
谁能解释为什么Herb可能会说这个?
为了从函数中返回一个字符串,这两个中的哪一个更有效(即我应该使用哪一个):
std::string f(const std::string& s)
{
return s + "some text";
}
Run Code Online (Sandbox Code Playgroud)
要么
void f(const std::string& s, std::string &result)
{
result = s + "some text";
}
Run Code Online (Sandbox Code Playgroud)
我明白答案可能取决于特定的编译器.但我想知道现代C++代码中推荐的方法(如果有的话)是什么.
根据下面的"轨道轻度竞赛"评论,这里是我在问到这个问题之前在stackoverflow上找到的一些相关问题:
将const std :: string&作为参数传递的日子是多少?
通过Value或Reference传递std :: string
"std :: string"或"const std :: string&"参数?(该参数在内部复制和修改)
这些都没有回答我关于从函数返回值而不是将字符串作为额外参数返回的特定问题.