Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ISO C++ forbids returning arrays?

Tags:

c++

arrays

c++14

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).

like image 739
AnArrayOfFunctions Avatar asked Nov 23 '14 17:11

AnArrayOfFunctions


1 Answers

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.

like image 111
Christophe Avatar answered Sep 25 '22 15:09

Christophe