I don't see any logical reason. I mean you can easily overcome the requirement by using a structure containing an array member like this:
template <size_t n>
struct arr { int d[n]; };
auto fnReturningArray()
{
return arr<3>{0, 1, 2};
};
Which will behave the exact same way as if the array is directly returned with the small difference that you should first access the structure member 'd' to use it. Also the standard itself have added similar functionality by the 'std::array' type. So it seems that it is implementation possible. Why then ISO C++ have forbidden this action? Maybe legacy code compatibility (but I can hardly believe this is the case as with the other new things added it is long gone, like for example the new meaning of the 'auto' keyword).
Beside the fact that the standard doesn't allow it, and the historical reasons that could explain it, the issue is syntactic:
Imagine it would be permitted : how would you distinguish the naming of the whole array, vs the array address, vs a single element:
auto fnReturningArray()
{
int a[3] = {0, 1, 2};
return a; // what is meant here ? the address of the array ? or the whole array ?
};
If you'd change the meaning of existing rules (such as tating that a would be the whole array), you would have huge problems with legacy code.
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