Kate
Kate

Reputation: 63

What is meaning of `T&` when returing `T` from function?

I see some code like this:

const std::vector<obj>& value = function();

And function() define as follow:

std::vector<obj> function()
{
   std::vector<obj> v {/* ... */};
   return v; 
}

What is meaning of & in const std::vector<obj>& value ? is get a reference or copy of local function() variable ?

Upvotes: 0

Views: 112

Answers (1)

Miles Budnek
Miles Budnek

Reputation: 30569

It is declaring value to be a reference to constant std::vector<obj>.

References that can bind to temporaries (references-to-const and rvalue-references) can extend the lifetime of the object they reference under some circumstances though, and this is one of those circumstances. That means that function's return value has its lifetime extended to the lifetime of value.

Pre-C++17 this could, in theory, avoid making an extra copy from the return value of function to value (though every compiler I know of would have elided the copy anyway). Since C++17 it's guaranteed that no copy is made, so lifetime-extension like this doesn't serve much of a purpose anymore.

Upvotes: 5

Related Questions