reinterpret_cast-ing 将一种类型的向量转换为相同类型的另一种类型的向量 [英] reinterpret_cast-ing vector of one type to a vector of another type which is of the same type

查看:38
本文介绍了reinterpret_cast-ing 将一种类型的向量转换为相同类型的另一种类型的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定问题是否在这里回答这个问题,因为措辞很奇怪,但是:

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

如果我有:

struct numpair
{
    some_type_with_a_size_of_2 a,b;
};

struct bignum
{
    some_type_with_a_size_of_4 a;
};

我可以将 bignums 向量重新解释为 numpairs 向量吗?如果没有,是否还有其他解决方法不需要我创建一个新向量并重新解释每个元素的转换?

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?

在我正在使用的 Visual Studio 2017 窗口上,这两种类型的大小相同.

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

我现在已经了解了这个严格的别名规则.这应该是二进制数据,用不同的界面查看.撇开 reinterpret_cast 不谈,我可以使用这些类型的向量的联合吗?

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?

推荐答案

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 左值和右值 [basic.lval]

§3.10 Lvalues and rvalues [basic.lval]

10 如果程序试图访问对象的存储值通过以下类型之一以外的泛左值行为未定义:54

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

  • 对象的动态类型,
  • 对象的动态类型的 cv 限定版本,
  • 类似于(如 4.4 中定义的)对象的动态类型的类型,
  • 与对象的动态类型对应的有符号或无符号类型,
  • 一种类型,它是与对象的动态类型的 cv 限定版本相对应的有符号或无符号类型,
  • 在其元素或非静态数据成员(包括,递归地,子聚合的元素或非静态数据成员或包含联合),
  • 一种类型,它是对象动态类型的(可能是 cv 限定的)基类类型,即 char 或 unsigned char 类型.

54) 此列表的目的是指定哪些情况一个对象可能有别名也可能没有别名.

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

这篇关于reinterpret_cast-ing 将一种类型的向量转换为相同类型的另一种类型的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆