在 C++ 中执行非静态成员变量结构体/类需要被标记为易失性才能在成员函数中被视为易失性吗?
class MyClass
{
int x, y;
void foo() volatile {
// do stuff with x
// do stuff with y
}
};
我是否需要将 x
和 y
声明为 易失性
还是将所有成员变量自动视为 易失性
?
我想确保“stuff with x
”不会被编译器重新排序为“stuff with y
”。
编辑: 如果我将普通类型转换为 易失性
类型,会发生什么情况?这是否会指示编译器不要重新排序对该位置的访问?我想将特殊情况下的普通变量传递给参数易失的函数。我必须确保编译器不会通过之前或之后的读取和写入重新排序该调用。
class MyClass
{
int x, y;
void foo() volatile {
// do stuff with x
// do stuff with y
}
};
Do I need to declare x
and y
as volatile
or will be all member variables treated as volatile
automatically?
I want to make sure that "stuff with x
" is not reordered with "stuff with y
" by the compiler.
EDIT:
What happens if I'm casting a normal type to a volatile
type? Would this instruct the compiler to not reorder access to that location? I want to pass a normal variable in a special situation to a function which parameter is volatile. I must be sure compiler doesn't reorder that call with prior or followed reads and writes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
标记成员函数
易失性
就像标记它const
;这意味着接收者对象被视为被声明为易失性T*
。因此,任何对x
或y
的引用都将被视为成员函数中的易失性
读取。此外,易失性
对象只能调用易失性
成员函数。也就是说,如果您确实希望将对
x
和y
和y
的所有访问都视为易失性。
Marking a member function
volatile
is like marking itconst
; it means that the receiver object is treated as though it were declared as avolatile T*
. Consequentially, any reference tox
ory
will be treated as avolatile
read in the member function. Moreover, avolatile
object can only callvolatile
member functions.That said, you may want to mark
x
andy
volatile
anyway if you really do want all accesses to them to be treated asvolatile
.您不必必须显式声明成员变量。
来自标准文档9.3.2.3,
You don't have to declare the member variables explicitly..
From Standard docs 9.3.2.3,
以下代码:
使用 gcc 编译时引发错误:
并且由于
易失性
实例无法调用非易失性
方法,我们可以假设,是的,x
和y
在方法中将是易失性
,即使MyClass
的实例未声明易失性< /代码>。
注意:如果需要,您可以使用
const_cast<>
删除volatile
限定符;但是要小心,因为就像const
一样,在某些情况下这样做可能会导致未定义的行为。The following code:
Raises an error upon compilation with gcc:
And since a
volatile
instance can't call anon-volatile
method, we can assume that, yes,x
andy
will bevolatile
in the method, even if the instance ofMyClass
is not declaredvolatile
.Note: you can remove the
volatile
qualifier using aconst_cast<>
if you ever need to; however be careful because just likeconst
doing so can lead to undefined behavior under some cases.所以使用原来的例子:
So using the original example: