Reputation: 9049
Can I return an array by value in C++? By value I mean returning a copy instead of using a pointer. If so can someone provide an example of returning a 1d array and a 2d array?
Upvotes: 1
Views: 179
Reputation: 6623
No this is impossible, unless you use some kind of custom array class (such as std::array as mentioned by Matteo Italia). Arrays in C/C++ are treated in much the same way as pointers.
Upvotes: 1
Reputation: 69988
No this is not allowed in C/C++ .
You can return array by reference, if it's not local to function. The other work around is to wrap it inside a 'struct/class' wrapper and return its object.
Upvotes: 1
Reputation: 126787
No; you can return arrays by value only by wrapping them inside a struct
or a class
(actually, you can simply return an appropriate instance of std::array
, which encapsulates a C-style array inside a template class which provides also some bells and whistles).
Upvotes: 6