Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return std::array by value

Tags:

c++

arrays

c++11

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?

like image 549
Violet Giraffe Avatar asked May 11 '26 03:05

Violet Giraffe


1 Answers

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.

like image 165
Hatted Rooster Avatar answered May 13 '26 17:05

Hatted Rooster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!