我最近听了Herb Sutter的一个演讲,他认为通过const &传递std::vector和std::string的原因已经基本消失了。他建议现在最好编写如下这样的函数:

std::string do_something ( std::string inval )
{
   std::string return_val;
   // ... do stuff ...
   return return_val;
}

我知道return_val在函数返回时将是一个右值,因此可以使用move语义返回,这非常便宜。然而,inval仍然比引用(通常实现为指针)的大小大得多。这是因为std::string有各种组件,包括指向堆的指针和用于短字符串优化的成员char[]。所以在我看来,通过引用传递仍然是一个好主意。

谁能解释一下赫伯为什么会这么说?


当前回答

Herb Sutter和Bjarne Stroustroup一起推荐使用const std::string&作为形参类型;见https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rf-in。

这里有一个在其他答案中没有提到的陷阱:如果你将一个字符串字面值传递给一个const std::string& parameter,它将传递一个临时字符串的引用,该字符串是动态创建的,用于保存字面值的字符。如果然后保存该引用,那么一旦释放临时字符串,它将无效。为了安全起见,您必须保存副本,而不是参考资料。这个问题源于字符串字面值是const char[N]类型,需要升级为std::string。

下面的代码说明了陷阱和解决方法,以及一个较小的效率选项——使用const char*方法重载,如在c++中是否有一种方法将字符串文字作为引用传递。

(注意:Sutter & Stroustroup建议,如果你保留了字符串的副本,也要提供一个带有&&形参和std::move()的重载函数。)

#include <string>
#include <iostream>
class WidgetBadRef {
public:
    WidgetBadRef(const std::string& s) : myStrRef(s)  // copy the reference...
    {}

    const std::string& myStrRef;    // might be a reference to a temporary (oops!)
};

class WidgetSafeCopy {
public:
    WidgetSafeCopy(const std::string& s) : myStrCopy(s)
            // constructor for string references; copy the string
    {std::cout << "const std::string& constructor\n";}

    WidgetSafeCopy(const char* cs) : myStrCopy(cs)
            // constructor for string literals (and char arrays);
            // for minor efficiency only;
            // create the std::string directly from the chars
    {std::cout << "const char * constructor\n";}

    const std::string myStrCopy;    // save a copy, not a reference!
};

int main() {
    WidgetBadRef w1("First string");
    WidgetSafeCopy w2("Second string"); // uses the const char* constructor, no temp string
    WidgetSafeCopy w3(w2.myStrCopy);    // uses the String reference constructor
    std::cout << w1.myStrRef << "\n";   // garbage out
    std::cout << w2.myStrCopy << "\n";  // OK
    std::cout << w3.myStrCopy << "\n";  // OK
}

输出:

Const char *构造函数 常量std::string&构造函数 第二个字符串 第二个字符串

其他回答

正如@ jduzgosz在评论中指出的那样,Herb在另一个(稍后?)谈话中给出了其他建议,大致可以从这里看到:https://youtu.be/xnqTKD8uD64?t=54m50s。

他的建议可以归结为,对于一个接受所谓汇聚参数的函数f,只使用值形参,假设您将从这些汇聚参数中移动construct。

与分别为左值和右值参数定制的f的最佳实现相比,这种通用方法只是同时为左值和右值参数增加了move构造函数的开销。要了解为什么会出现这种情况,假设f接受一个值形参,其中T是某个复制和移动构造类型:

void f(T x) {
  T y{std::move(x)};
}

使用左值参数调用f将导致调用一个复制构造函数来构造x,调用一个移动构造函数来构造y。另一方面,使用右值参数调用f将导致调用一个移动构造函数来构造x,并调用另一个移动构造函数来构造y。

一般来说,f对左值参数的最佳实现如下:

void f(const T& x) {
  T y{x};
}

在这种情况下,只调用一个复制构造函数来构造y。对于右值参数,f的最佳实现通常如下所示:

void f(T&& x) {
  T y{std::move(x)};
}

在这种情况下,只调用一个move构造函数来构造y。

因此,一个明智的妥协是,取一个value形参,并有一个额外的move构造函数调用,用于左值或右值参数,这也是Herb在演讲中给出的建议。

正如@ jdlugosz在评论中指出的那样,仅对将从sink参数构造某个对象的函数才有意义。当函数f复制其实参时,按值传递的方法比一般的按常量引用传递的方法开销更大。保留形参副本的函数f的值传递方法将具有如下形式:

void f(T x) {
  T y{...};
  ...
  y = std::move(x);
}

在这种情况下,左值实参有一个复制构造和一个move赋值,右值实参有一个move构造和move赋值。左值参数的最佳情况是:

void f(const T& x) {
  T y{...};
  ...
  y = x;
}

这可以归结为仅进行赋值操作,这可能比值传递方法所需的复制构造函数加移动赋值要便宜得多。这样做的原因是赋值可能会重用y中现有的已分配内存,因此防止(取消)分配,而复制构造函数通常会分配内存。

对于右值实参,保留副本的f的最优实现形式为:

void f(T&& x) {
  T y{...};
  ...
  y = std::move(x);
}

这里只有一个move赋值。将右值传递给接受const引用的f版本只需要赋值,而不是move赋值。所以相对而言,在这种情况下,f的版本采用const引用作为通用实现更可取。

So in general, for the most optimal implementation, you will need to overload or do some kind of perfect forwarding as shown in the talk. The drawback is a combinatorial explosion in the number of overloads required, depending on the number of parameters for f in case you opt to overload on the value category of the argument. Perfect forwarding has the drawback that f becomes a template function, which prevents making it virtual, and results in significantly more complex code if you want to get it 100% right (see the talk for the gory details).

IMO使用c++引用std::string是一个快速而简短的局部优化,而使用传递值可能是(或不是)一个更好的全局优化。

所以答案是:这取决于环境:

如果你把所有的代码从外部写到内部函数,你知道代码是做什么的,你可以使用引用const std::string &。 如果您编写库代码,或者在传递字符串的地方大量使用库代码,那么通过信任std::string复制构造函数行为,您可能会获得更多全局意义上的好处。

简单的回答:不!长一点的回答:

如果不修改字符串(treat是只读的),则将其作为const ref&传递。(const ref&显然需要在使用它的函数执行时保持在作用域内) 如果你打算修改它,或者你知道它将超出范围(线程),将它作为一个值传递,不要在函数体中复制const ref&。

在cpp-next.com网站上有一篇文章叫做“想要速度,而不是价值!”TL;博士:

指南:不要复制函数参数。相反,应该按值传递它们,并让编译器执行复制。

^的翻译

不要复制你的函数实参——意思是:如果你打算通过将实参复制到内部变量来修改实参值,只需使用一个值实参即可。

所以,不要这样做:

std::string function(const std::string& aString){
    auto vString(aString);
    vString.clear();
    return vString;
}

这样做:

std::string function(std::string aString){
    aString.clear();
    return aString;
}

当您需要修改函数体中的参数值时。

您只需要注意计划如何在函数体中使用参数。只读或非只读…如果它在范围内。

我复制/粘贴了这个问题的答案,并更改了名称和拼写以适应这个问题。

下面是用来衡量问题的代码:

#include <iostream>

struct string
{
    string() {}
    string(const string&) {std::cout << "string(const string&)\n";}
    string& operator=(const string&) {std::cout << "string& operator=(const string&)\n";return *this;}
#if (__has_feature(cxx_rvalue_references))
    string(string&&) {std::cout << "string(string&&)\n";}
    string& operator=(string&&) {std::cout << "string& operator=(string&&)\n";return *this;}
#endif

};

#if PROCESS == 1

string
do_something(string inval)
{
    // do stuff
    return inval;
}

#elif PROCESS == 2

string
do_something(const string& inval)
{
    string return_val = inval;
    // do stuff
    return return_val; 
}

#if (__has_feature(cxx_rvalue_references))

string
do_something(string&& inval)
{
    // do stuff
    return std::move(inval);
}

#endif

#endif

string source() {return string();}

int main()
{
    std::cout << "do_something with lvalue:\n\n";
    string x;
    string t = do_something(x);
#if (__has_feature(cxx_rvalue_references))
    std::cout << "\ndo_something with xvalue:\n\n";
    string u = do_something(std::move(x));
#endif
    std::cout << "\ndo_something with prvalue:\n\n";
    string v = do_something(source());
}

对我来说,这输出:

$ clang++ -std=c++11 -stdlib=libc++ -DPROCESS=1 test.cpp
$ a.out
do_something with lvalue:

string(const string&)
string(string&&)

do_something with xvalue:

string(string&&)
string(string&&)

do_something with prvalue:

string(string&&)
$ clang++ -std=c++11 -stdlib=libc++ -DPROCESS=2 test.cpp
$ a.out
do_something with lvalue:

string(const string&)

do_something with xvalue:

string(string&&)

do_something with prvalue:

string(string&&)

下表总结了我的结果(使用clang -std=c++11)。第一个数字是复制结构的数量,第二个数字是移动结构的数量:

+----+--------+--------+---------+
|    | lvalue | xvalue | prvalue |
+----+--------+--------+---------+
| p1 |  1/1   |  0/2   |   0/1   |
+----+--------+--------+---------+
| p2 |  1/0   |  0/1   |   0/1   |
+----+--------+--------+---------+

值传递解决方案只需要一次重载,但在传递左值和x值时需要额外的move构造。对于任何特定的情况,这可能是可接受的,也可能是不可接受的。这两种解决方案各有优缺点。

赫伯说那些话的原因就是因为这样的案子。

假设我有一个函数A,它调用函数B,函数B调用函数C, A将一个字符串通过B传递给C, A不知道也不关心C;A只知道B,也就是说,C是B的一个实现细节。

假设A的定义如下:

void A()
{
  B("value");
}

如果B和C通过const&获取字符串,那么它看起来像这样:

void B(const std::string &str)
{
  C(str);
}

void C(const std::string &str)
{
  //Do something with `str`. Does not store it.
}

一切都很好。你只是传递指针,没有复制,没有移动,每个人都很开心。C接受一个参数&,因为它不存储字符串。它只是简单地使用它。

现在,我想做一个简单的改变:C需要将字符串存储在某个地方。

void C(const std::string &str)
{
  //Do something with `str`.
  m_str = str;
}

你好,复制构造函数和潜在的内存分配(忽略短字符串优化(SSO))。c++ 11的move语义应该可以消除不必要的复制构造,对吧?A只是暂时的;C没有理由复制数据。它应该带着给它的东西潜逃。

但它不能。因为它需要一个常量。

如果我改变C的参数值,这只会导致B对参数进行复制;我什么也得不到。

所以如果我在所有函数中都按值传递str,依靠std::move来打乱数据,我们就不会有这个问题。如果有人想留住它,他们可以做到。如果没有,那好吧。

会更贵吗?是的,移动到值中比使用引用代价更大。它比复制品便宜吗?不适合使用SSO的小字符串。值得做吗?

这取决于您的用例。你有多讨厌内存分配?