C ++ volatile成员函数 [英] C++ volatile member functions

查看:513
本文介绍了C ++ volatile成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class MyClass
{
    int x, y;
    void foo() volatile {
        // do stuff with x
        // do stuff with y
    }   
};

我需要将'x'和'y'声明为volatile或将成为所有成员变量as volatile volatile?

Do I need to declare 'x' and 'y' as volatile or will be all member variables treated as volatile automatically?

我想确保stuff with'x'不会被编译器的stuff with'y'重新排序。

I want to make sure that "stuff with 'x'" is not reordered with "stuff with 'y'" by the compiler.

编辑:
如果我将正常类型转换为volatile类型,会发生什么?这将指示编译器不重新排序对该位置的访问?我想在一个特殊情况下传递一个正常变量给一个函数,其参数是volatile。

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.

推荐答案

标记成员函数 volatile 就像标记 const ;这意味着接收器对象被视为被声明为 volatile T * 。因此,对 x y 的任何引用将被视为 volatile 读入成员函数。此外, volatile 对象只能调用 volatile 成员函数。

Marking a member function volatile is like marking it const; it means that the receiver object is treated as though it were declared as a volatile T*. Consequentially, any reference to x or y will be treated as a volatile read in the member function. Moreover, a volatile object can only call volatile member functions.

也就是说,您可以标记 x y volatile 无论如何,如果你确实希望对它们的所有访问被视为 volatile

That said, you may want to mark x and y volatile anyway if you really do want all accesses to them to be treated as volatile.

这篇关于C ++ volatile成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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