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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With