I've seen code like const auto& now = time(nullptr);
I think the purpose of assigning the rvalue returned by time
is to extend the return value's lifetime, as explained in the GotW post. But why not use const auto now = time(nullptr)
?
Why do we want to extend the lifetime of the return value here? and is there any performance difference?
In the shown example, there is no reason to use a reference. The behavior of the snippet is identical with or without it.
In general, it's a good idea to use a reference to avoid incurring needless copies, so there's no harm in getting into the habit of using references, even if it doesn't make a difference in some cases.
I'd suggest writing const
on the east though. This is just a preference, and definitely doesn't change the meaning of the code, but it's more consistent. I would write it as:
auto const & now = time(nullptr);