使用const引用返回值的值

bri*_*ner 4 c++ reference return-value rvo nrvo

请看以下示例:

string foo(int i) {
  string a;
  ... Process i to build a ...
  return a;
}

void bar(int j) {
  const string& b = foo(j);
  cout << b;
}
Run Code Online (Sandbox Code Playgroud)

我知道RVO和NRVO,但我认为为了做到这一点,我需要写下如下栏:

void bar(int j) {
  string b = foo(j);
  cout << b;
}
Run Code Online (Sandbox Code Playgroud)

两个版本似乎都有效,我相信具有相同的性能.使用第一个版本(使用const引用)是否安全?

谢谢.

Fer*_*yer 6

将临时值分配给const引用是完全有效的.临时对象将一直存在,直到引用超出范围.

虽然在您的示例中没有意义,但此功能通常用于函数参数:

string foo(int i) {
    string a;
    // ...
    return a;
}

void bar(const string& str) {
    // ...
}

void buzz() {
    // We can safely call bar() with the temporary string returned by foo():
    bar(foo(42));
}
Run Code Online (Sandbox Code Playgroud)

  • 对于一直使用的情况+1.:) (2认同)