What's the best way to return a tuple from function in C++11?

Gian Lorenzo Meocci picture Gian Lorenzo Meocci · May 23, 2013 · Viewed 11k times · Source

I want to return some values from a function and I want to pack it in a tuple. So I have two possibilities for function declaration:

std::tuple<bool, string, int> f()
{
  ...
  return std::make_tuple(false, "home", 0);
}

and

std::tuple<bool, string, int> f()
{
  ...
  return std::forward_as_tuple(false, "home", 0);
}

These functions are equivalents? Between these functions which do you prefer?

Answer

Andy Prowl picture Andy Prowl · May 23, 2013

std::forward_as_tuple() creates a tuple of references. Since you are returning a tuple<bool, string, int> anyway, the two end up being equivalent in this case, but I think the first approach is clearer - using forward_as_tuple() when you are not forwarding anything is confusing.

Also, as mentioned by Sebastian Redl in the comments, make_tuple() would allow the compiler to perform copy elision - per paragraph 12.8/31 of the C++11 Standard, while forward_tuple() would not (since what it returns does not have the same type as the function's return type).