2014-08-12

How the lifetime of temporaries is extended because of references in C++

This blog post summarizes what I learned about C++ today about how the lifetime of temporaries is extended because of references.

Normally a temporary is destroyed at the end of the statement, for example temporary string returned by GetName() lives until the end of the line defining name. (There is also the return value optimization which may eliminate the temporary.)

#include <stdio.h>

#include <string>
using std::string;
string GetName() {
  return string("foo") + "bar";
}
int main() {
  string name = GetName();
  printf("name=(%s)\n", name.c_str());
  return 0;
}

However, it's possible to extend the life of the temporary by assigning it to a reference-typed local variable. In that case, the temporary will live until the corresponding reference variable goes out of scope. For example, this will also work and it's equivalent to above:

#include <stdio.h>
int main() {
  const string &name = GetName();
  printf("name=(%s)\n", name.c_str());
  return 0;
}

Please note that there is no lifetime extension if the function returns a reference, and also in some other cases related to function boundaries. See more details about reference initialization.

No comments: