问题
Why is the following code frowned upon?
double d[4] = {0,1,2,3};
reinterpret_cast<double[2]>(d);
GCC declares it an invalid cast from type 'double*' to type 'double [2]'
and clang declares that reinterpret_cast from 'double *' to 'double [2]' is not allowed
Now in case the intent is not obvious, I would like this code to return a double[2] that contains {0,1}, pretty much like a reinterpret_cast<double*>(d)
would. (Hence I know it would work with pointers, so that's not what I'm asking)
回答1:
Both compilers are correct.
reinterpret_cast
is not a hammer, it's a powerful precision tool. All uses of reinterpret_cast
have to involve at least one pointer or reference type as the source or as the destination, except for the degenerate case of an identity integral conversion (i.e. reinterpret_cast
from int
to int
is allowed and does nothing.)
回答2:
What you may want is
double (&d2)[2] = reinterpret_cast<double(&)[2]>(d);
回答3:
You have an array (not a pointer) of size 4. You cannot cast it to an array of size 2 because of the simple fact that the size is incorrect. A similar example is that you couldn't cast an instance of a class to an instance of a class to an instance of another class, because that just doesn't make any sense. To get an array with {0,1}
you have to make a whole new array.
Here's the right way to do it:
double d[4] = {0,1,2,3};
double copy[2]{};
std::copy_n(std::begin(d),2,std::begin(copy));
If you don't want to create a copy of the array the idiomatic thing to do is operate on a range instead of an array, there is a reason every algorithm in the standard lib operates on iterators not containers.
来源:https://stackoverflow.com/questions/18514490/is-reinterpret-cast-to-c-style-array-illegal-c11