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

落爺英雄遲暮 提交于 2020-01-17 15:14:05

问题


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?


回答1:


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.




回答2:


$ 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?



来源:https://stackoverflow.com/questions/46044682/reinterpret-cast-ing-vector-of-one-type-to-a-vector-of-another-type-which-is-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!