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)

有帮助吗?

解决方案 2

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

其他提示

What you may want is

double (&d2)[2] = reinterpret_cast<double(&)[2]>(d);

Not sure it is not pedantically undefined behavior though (as most usage of reinterpret_cast).

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top