内容简介: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 *意味着它不能实际上任何类型的别名?
:
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
a
, a reference that referredthe name of the original object will
and, once the lifetime of thenew object has started, can be used to manipulate the new object, if :
(7.1) — [..]
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
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- Git命令别名设置
- mybatis的typeAliases别名
- Elasticsearch基础但非常有用的功能之一:别名
- Elasticsearch索引的基本操作(5)-别名设置
- Elasticsearch 技术分析(三): 索引别名Aliases问题
- javascript – 摆脱SVG循环元素上的别名
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
像计算机科学家一样思考Python
(美)Allen B.Downey / 赵普明 / 人民邮电出版社 / 2013-8 / 49
《像计算机科学家一样思考python》按照培养读者像计算机科学家一样的思维方式的思路来教授python语言编程。全书贯穿的主体是如何思考、设计、开发的方法,而具体的编程语言,只是提供一个具体场景方便介绍的媒介。《像计算机科学家一样思考python》并不是一本介绍语言的书,而是一本介绍编程思想的书。和其他编程设计语言书籍不同,它不拘泥于语言细节,而是尝试从初学者的角度出发,用生动的示例和丰富的练习来......一起来看看 《像计算机科学家一样思考Python》 这本书的介绍吧!