reinterpret_cast-ing vector of one type to a vector of another type which is of the same type

878 Views Asked by At

I'm not sure if the question here answers this question due to the weird wording, but:

if i have:

struct numpair
{
    some_type_with_a_size_of_2 a,b;
};

struct bignum
{
    some_type_with_a_size_of_4 a;
};

Can I reinterpret_cast a vector of bignums to a vector of numpairs? If not, are there other workarounds that don't require me to make a new vector and go through reinterpret casting each element?

edit: on visual studio 2017 windows, which i am using, these two types are the same size.

edit: I have now learned if this strict aliasing rule. This is supposed to be binary data, viewed with different interfaces. Putting aside reinterpret_cast, could I possibly use a union of vectors of these types?

2

There are 2 best solutions below

6
On
$ cat omg.cpp && g++ omg.cpp && echo ========== && ./a.out
#include <iostream>

struct numpair {
    unsigned short a,b;
};

struct bignum {
    unsigned long a;
};

int main() {
    std::cout << sizeof(numpair) << " != " << sizeof(bignum) << std::endl;
}
==========
4 != 8

Why do you think the types are the same?

0
On
struct A
{
    int x;
};

struct B
{
    int x;
};

You can't even reinterpret cast between these two types. It would violate the strict aliasing rule. So no, you cannot do what you want.

§3.10 Lvalues and rvalues [basic.lval]

10 If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:54

  • the dynamic type of the object,
  • a cv-qualified version of the dynamic type of the object,
  • a type similar (as defined in 4.4) to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
  • a type that is a (possibly cv-qualified) base class type of the dynamic type of the object, — a char or unsigned char type.

54) The intent of this list is to specify those circumstances in which an object may or may not be aliased.