c++ 这是否真的破坏了严格的别名规则?

栏目: C++ · 发布时间: 7年前

内容简介:http://stackoverflow.com/questions/27003727/does-this-really-break-strict-aliasing-rules

当我用g编译这个示例代码时,我得到这个警告:

warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]

代码:

#include <iostream>

int main() 
{
   alignas(int) char data[sizeof(int)];
   int *myInt = new (data) int;
   *myInt = 34;

   std::cout << *reinterpret_cast<int*>(data);
}

在这种情况下,数据别名不是int,因此将其返回到int不会违反严格的别名规则?还是我在这里遗漏的东西?

编辑:奇怪,当我定义这样的数据:

alignas(int) char* data = new char[sizeof(int)];

编译器警告消失了.堆栈分配是否与严格的混叠有所不同?事实上,它是一个char []而不是一个char *意味着它不能实际上任何类型的别名?

警告是绝对合理的.指向数据的衰减指针不指向int类型的对象,并且转换它不会改变.见 [basic.life]/7

If, after the lifetime of an object has ended and before the storage

which the object occupied is reused or released, a new object is

created at the storage location which the original object occupied,

a

, a reference that referred
to the original object, or

the name of the original object will

and, once the lifetime of the

new object has started, can be used to manipulate the new object, if :

(7.1) — [..]

(7.2) —

the new object is of the same type as the

original object (ignoring the top-level cv-qualifiers)

,

新对象不是一个char数组,而是一个int. P0137 ,正式化了指点的概念,添加了洗衣:

[ Note : If these conditions are not met, a pointer to the new object

can be obtained from a pointer that represents the address of its

storage by calling std::launder (18.6 [support.dynamic]). — end note

]

即您的代码段可以这样纠正:

std::cout << *std::launder(reinterpret_cast<int*>(data));

..或者只是从放置新的结果初始化一个新的指针,这也消除了警告.

http://stackoverflow.com/questions/27003727/does-this-really-break-strict-aliasing-rules


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

长尾理论

长尾理论

[美] 克里斯·安德森 / 乔江涛 / 中信出版社 / 2006-12 / 35.00元

书中阐述,商业和文化的未来不在于传统需求曲线上那个代表“畅销商品”(hits)的头部; 而是那条代表“冷门商品”(misses)经常为人遗忘的长尾。 举例来说, 一家大型书店通常可摆放10万本书,但亚马逊网络书店的图书销售额中,有四分之一来自排名10万以后的书籍。这些“冷门”书籍的销售比例正以高速成长,预估未来可占整体书市的一半。 这意味着消费者在面对无限的选择时,真正想要的东西、和想要取得......一起来看看 《长尾理论》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具