首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用reinterpret_cast<>的Boolean_conversions

使用reinterpret_cast<>的Boolean_conversions
EN

Stack Overflow用户
提问于 2010-12-03 17:39:04
回答 3查看 914关注 0票数 0

谁能举个例子来说明

代码语言:javascript
复制
 Boolean_conversions Using  reinterpret_cast<>

我得到了execution failure..Any one解释。

例如:

代码语言:javascript
复制
   void Boolean_Conversions()
     {
         bool b = 0;
         int *i = reinterpret_cast<int*> (&b);
  // iam expecting as *i is 0/false    ,but it is showing runtime error          
     }

编辑:在ISO标准部分$5.2.10,第1段:

代码语言:javascript
复制
      "The result of the expression reinterpret_cast<T>(v) is the
  result of converting the expression v to type T. If T is a
  reference type, the result is an lvalue; otherwise, the re
  sult is an rvalue and the l-value to r-value (4.1), array
  to pointer (4.2), and function to pointer (4.3) standard c
  onversions are performed on the the expression v. Types sh
  all not be defined in a reinterpret_cast."

从这个我尝试..I做了很多转换,..like Array_to_Pointer,Function_To_Pointer,Integral/Pointer_Conversion,etc...But,我不知道为什么布尔转换失败。

有人能说出失败的原因吗?用reinterpret_cast告诉Boolean COnversions。

主要是在G++.cc/EDG/codepad..等编译器中导致运行时失败

请解释一下

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-12-03 18:04:48

否,未定义输出。请注意,转换是未定义的。

在我的机器上*i = 0xcccccc00

注意lsb是00

其对应于用0(假)初始化的bool变量的值。其他三个字节中的字节模式(假设int的大小为32位)是完全未指定的,并取决于该内存/字节顺序等中的内容。

然而,从技术上讲,这是一种未定义的行为,因为我们推迟了我们没有保留/分配的内存位置(全部)。

票数 2
EN

Stack Overflow用户

发布于 2010-12-03 18:09:41

你仍然不清楚你想要做什么!例如,您是否知道有三种类型转换:

代码语言:javascript
复制
TO_TYPE DEST_VAL = static_cast<TO_TYPE>(SOME_VAL);

TO_TYPE DEST_VAL = dynamic_cast<TO_TYPE>(SOME_VAL);

还有你挂在上面的那个:

代码语言:javascript
复制
TO_TYPE DEST_VAL = reinterpret_cast<TO_TYPE>(SOME_VAL);

在这三个中,最后一个是最危险的,基本上你忽略了编译器告诉你的所有关于类型的事情,并强迫你去做!这意味着你知道你在做什么,但在大多数情况下,你不知道。

通常,当其他两个强制转换不能满足您的需要时,您应该只使用最后一个作为最后的手段,并且您已经仔细查看了设计,并咨询了占卜者等!它不是类型安全的,并且它不能保证结果对象是您期望的对象,就像您在上面尝试做的那样。boolint可能具有也可能不具有相同的对齐存储,并使用指针指向bool的地址,而应该指向指向int,并且取消引用可能导致潜在地访问所有类型的内存下层区域...

票数 1
EN

Stack Overflow用户

发布于 2010-12-03 17:45:05

代码语言:javascript
复制
bool b = 0;
int *i = reinterpret_cast<int*> (&b);

这将在将b的内存地址“转换”为适合int指针的样式后,将其存储到i。如果您想要向int强制转换bool,只需这样做

代码语言:javascript
复制
int i = reinterpret_cast<int> (b);

如果bfalse,则确实为0,否则为1。不过,你不需要reinterpret_cast<int>。阅读帖子上的其他评论,它就会变得清晰。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4344201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档