gpt4 book ai didi

C++:reinterpret_cast 的奇怪行为

转载 作者:太空宇宙 更新时间:2023-11-04 15:34:30 25 4
gpt4 key购买 nike

我有以下片段

#include <iostream>

using namespace std;

class foobar
{
public:
unsigned int a = 97;
unsigned int b = 98;
unsigned int c = 99;
};


class barfoo
{
public:
char a:32,b:32,c;

};


int main(){
foobar * f = new foobar();
barfoo * b = (reinterpret_cast<barfoo *>(f));
cout << b->a << "-" << b->b << "-" << b->c;

}

输出:

a-b-c

但是,如果我在 barfoo 中指定了 c 的宽度,它就不起作用(所有值都是 0)。观察

#include <iostream>

using namespace std;

class foobar
{
public:
unsigned int a = 97;
unsigned int b = 98;
unsigned int c = 99;
};


class barfoo
{
public:
char a:32,b:32,c:32;

};


int main(){
foobar * f = new foobar();
barfoo * b = (reinterpret_cast<barfoo *>(f));
cout << b->a << "-" << b->b << "-" << b->c;

}

输出:

--

字符全为0

知道为什么会这样吗?

ideone 链接 first snippet -- 工作

链接到ideone second snippet -- 不工作

编译器是gcc-5.1谢谢!!

最佳答案

reinterpret_cast 不满足已定义行为的要求,因此虽然对其结果的赋值是可接受的,但 b 的任何后续访问都是未定义的行为:

barfoo * b = (reinterpret_cast<barfoo *>(f));

A reinterpret_cast必须满足以下条件之一,其中 foobar 是 DynamicType,barfoo 是 AliasedType:

  • AliasedType is (possibly cv-qualified) DynamicType
  • AliasedType and DynamicType are both (possibly multi-level, possibly cv-qualified at each level) pointers to the same type T
  • AliasedType is the (possibly cv-qualified) signed or unsigned variant of DynamicType
  • AliasedType is an aggregate type or a union type which holds one of the aforementioned types as an element or non-static member (including, recursively, elements of subaggregates and non-static data members of the contained unions): this makes it safe to obtain a usable pointer to a struct or union given a pointer to its non-static member or element.
  • AliasedType is a (possibly cv-qualified) base class of DynamicType
  • AliasedType is char or unsigned char: this permits examination of the object representation of any object as an array of unsigned char.

由于 AliasedType 不属于任何这些条件,因此访问 reinterpret_cast 的结果是未定义的行为。

关于C++:reinterpret_cast 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38349388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com