严格的指针别名:是通过一个“volatile”指针/引用访问一个解决方案? [英] Strict pointer aliasing: is access through a 'volatile' pointer/reference a solution?

查看:129
本文介绍了严格的指针别名:是通过一个“volatile”指针/引用访问一个解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特定问题的脚步,自我回答和评论,我想了解它是否是一个正确的解决方案,解决方法/黑客或只是简单的错误。

On the heels of a specific problem, a self-answer and comments to it, I'd like to understand if it is a proper solution, workaround/hack or just plain wrong.

具体来说,我重写了代码:

Specifically, I rewrote code:

T x = ...;
if (*reinterpret_cast <int*> (&x) == 0)
  ...

As:

T x = ...;
if (*reinterpret_cast <volatile int*> (&x) == 0)
  ...

$

让我们假设一个指针的
$ b <在我的情况下将 T 视为 int 通过 volatile 引用访问是否解决了指针别名问题?

Let's just assume that treating T as int in my situation makes sense. Does this accessing through a volatile reference solve pointer aliasing problem?

>

For a reference, from specification:


[注意:volatile是一个提示,避免积极的
优化涉及对象,因为对象的值可能
通过实现不可检测的方式改变。请参见1.9的
详细语义。一般来说,volatile的语义是
,在C ++中和C一样。 - end note]

[ Note: volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation. See 1.9 for detailed semantics. In general, the semantics of volatile are intended to be the same in C++ as they are in C. — end note ]

编辑:

上述代码至少在GCC 4.5上解决了我的问题。

The above code did solve my problem at least on GCC 4.5.

推荐答案

Volatile不能帮助你避免未定义的行为。所以,如果它适用于你与GCC它的运气。

Volatile can't help you avoid undefined behaviour here. So, if it works for you with GCC it's luck.

让我们假设T是一个POD。然后,正确的方法是

Let's assume T is a POD. Then, the proper way to do this is

T x = …;
int i;
memcpy(&i,&x,sizeof i);
if (i==0)
  …

没有严格的别名问题,也没有内存对齐问题。 GCC甚至将memcpy作为内在函数处理(在这种情况下不插入函数调用)。

There! No strict aliasing problem and no memory alignment problem. GCC even handles memcpy as an intrinsic function (no function call is inserted in this case).

这篇关于严格的指针别名:是通过一个“volatile”指针/引用访问一个解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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