AnArrayOfFunctions
AnArrayOfFunctions

Reputation: 3754

Why ISO C++ forbids returning arrays?

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

Upvotes: 9

Views: 623

Answers (2)

rubenvb
rubenvb

Reputation: 76775

The answer as I see it, is twofold:

  1. Compatibility with C. C doesn't work this way. Why? No idea. C never was very logical to begin with in various aspects.

  2. C++ prefers library features over language features. Seeing that C++98 was the first standard, and it mostly copied the basics from C (see point 1), this was corrected in the first major revision, C++11, which introduces the library type std::array, which, as a pure and simple library feature, solves all the abhorrent quirks that C-style arrays entail.

To summarise: even though it might make sense to have proper value semantics for arrays, it will never happen, because the apparent deficiency can be solved without making the language more complex than it already is. It is extremely difficult to get rid of legacy and backwards compatibility, so the current option of std::array is really what you want. Use it. It's simple. You'll like it. A lot.

Upvotes: 0

Christophe
Christophe

Reputation: 73530

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.

Upvotes: 2

Related Questions