lundi 26 octobre 2020

Is it legal to convert a pointer/reference to a fixed array size to a smaller size

Is it legal as per the C++ standard to convert a pointer or reference to a fixed array size (e.g. T(*)[N] or T(&)[N]) to a pointer or reference of a smaller fixed array size of the same type and CV qualification (e.g. T(*)[M] or T(&)[M])?

Basically, would an example similar to the following be well-formed:

#include <string> // std::char_traits

void set_value(std::string(&array)[2])
{
    array[0] = "hello";
    array[1] = "world";
}

void receive(std::string(&array)[6])
{
    set_value(reinterpret_cast<std::string(&)[2]>(array));
}

I don't see any references to this being a valid conversion in:

However, it appears that all major compilers accept this and generate proper code (compiler explorer).

It's my understanding that this should be illegal as per the type-system, since an object of std::string[2] was never truly created, which means a reference of std::string(&)[2] would be invalid.

In case whether T is standard-layout plays a role: Let's assume that T is not always of standard layout type.


I'm tagging this question because this is the version I am stuck using, but I would be curious to know whether this answer varies in newer versions a well.

Aucun commentaire:

Enregistrer un commentaire