相关疑难解决方法(0)

将const std :: string&作为参数传递的日子是多少?

我听取了香草萨特最近的谈话谁建议的理由来传递std::vectorstd::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可能会说这个?

c++ c++11

579
推荐指数
11
解决办法
17万
查看次数

是应该通过函数的值还是通过"std :: string&s"作为参数返回std :: string?

为了从函数中返回一个字符串,这两个中的哪一个更有效(即我应该使用哪一个):

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

通过值或const引用?

"std :: string"或"const std :: string&"参数?(该参数在内部复制和修改)

这些都没有回答我关于从函数返回值而不是将字符串作为额外参数返回的特定问题.

c++ string performance c++11

1
推荐指数
1
解决办法
4830
查看次数

标签 统计

c++ ×2

c++11 ×2

performance ×1

string ×1