C / C ++:虚掷挥发性认为是有害的? [英] C/C++: casting away volatile considered harmful?

查看:115
本文介绍了C / C ++:虚掷挥发性认为是有害的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(有关这一问题的是安全的荒岛余生波动?,但并不完全一样,因为这个问题涉及特定实例)

(related to this question Is It Safe to Cast Away volatile?, but not quite the same, as that question relates to a specific instance)

是否有过在这里虚掷情况下挥发性是的的认为是一种危险的做法?

Is there ever a case where casting away volatile is not considered a dangerous practice?

(一个特殊的例子:如果有声明的函数

(one particular example: if there is a function declared

void foo(long *pl);

和我要实现

void bar(volatile long *pl);

我需要实施栏的一部分()来调用foo(PL),然后好像我不能得到这个作为是工作,是因为()由富的编制所做的假设和的编译酒吧的调用者()是不兼容的。)

with part of my implementation requiring bar() to call foo(pl), then it seems like I can't get this to work as is, because the assumptions made by the compilation of foo() and the compilation of the caller of bar() are incompatible.)

作为推论,如果我有一个挥发性变量v,我想打电话给富(安培; 5)别人的功能无效美孚(长* PL),那人告诉我它是安全的,我可以在呼叫之前只投的指针,我的直觉是要告诉他们,他们就错了,因为没有办法保证,他们应该改变声明无效美孚(挥发性长* ​​PL),如果他们想支持使用volatile变量。我们中的哪一个是正确的?

As a corollary, if I have a volatile variable v, and I want to call foo(&v) with someone else's function void foo(long *pl), and that person tells me it's safe, I can just cast the pointer before the call, my instinct is to tell them they're wrong because there's no way to guarantee that, and that they should change the declaration to void foo(volatile long *pl) if they want to support the use of volatile variables. Which one of us is correct?

推荐答案

如果该变量的声明 挥发性那么它的未定义行为以丢掉挥发性,只是因为它是不确定的行为从一个抛弃了常量变量声明常量。见C标准的附录J.2:

If the variable is declared volatile then it is undefined behaviour to cast away the volatile, just as it is undefined behaviour to cast away the const from a variable declared const. See Annex J.2 of the C Standard:

该行为是在下列情况下未定义:

The behavior is undefined in the following circumstances:

...

- 一个试图通过修改与一个常量限定类型定义的对象
  用非const限定型(6.7.3)。

— An attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type (6.7.3).

- 一个尝试是指与挥发性限定类型通过定义的对象
  使用具有非易失性限定类型(6.7.3)左值的。

— An attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type (6.7.3).

不过,如果你只是有一个挥发性指针或挥发性引用到非 - 挥发性变量,那么你可以随意抛弃挥发性

If, however, you just have a volatile pointer or a volatile reference to a non-volatile variable then you can freely cast away volatile.

volatile int i=0;
int j=0;

volatile int* pvi=&i; // ok
volatile int* pvj=&j; // ok can take a volatile pointer to a non-volatile object

int* pi=const_cast<int*>(pvi); // Danger Will Robinson! casting away true volatile
int* pj=const_cast<volatile int*>(pvj); // OK
*pi=3; // undefined behaviour, non-volatile access to volatile variable
*pj=3; // OK, j is not volatile

这篇关于C / C ++:虚掷挥发性认为是有害的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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