Reputation: 33579
A simple question, but I can't figure out the answer, neither on SO, nor on cppreference.com and similar sites.
Is it legal to return std::array
by value, like so?
std::array<int, 3> f() {
return std::array<int, 3> {1, 2, 3};
}
If it is legal, then it's also legal to pass it to functions by value, right?
Upvotes: 9
Views: 10348
Reputation: 36473
Yes it's legal. It's one of the advantages of using it over a C style array, it doesn't decay. It'll do what you expect it to do, copy the array element wise, in this case it'll just invoke RVO though.
As already said in the comments though, your second version is not safe. It'll construct a temporary and return it by ref, that'll cause you to end up with a dangling r ref.
Upvotes: 20