c++ - 定义 volatile 类对象

标签 c++ volatile

volatile 可以用于类对象吗? 喜欢:

volatile Myclass className;

问题是它不能编译, 当调用某些方法时,到处都会出现错误: 错误 C2662:“函数”:无法将“this”指针从“volatile MyClass”转换为“MyCLass &”

这里有什么问题,如何解决?

编辑:

class Queue {
            private:
                struct Data *data;
                int amount;
                int size;
            public:
                Queue ();
                ~Queue ();
                bool volatile push(struct Data element);
                bool volatile pop(struct Data *element);
                void volatile cleanUp();
            };
    .....
    volatile Queue dataIn;

        .....

    EnterCriticalSection(&CriticalSection);
    dataIn.push(element);
    LeaveCriticalSection(&CriticalSection);

最佳答案

是的,你可以,但是你只能调用声明为 volatile 的成员函数(就像 const 关键字一样)。例如:

 struct foo {
    void a() volatile;
    void b();
 };

 volatile foo f;
 f.a(); // ok
 f.b(); // not ok

根据您的代码进行编辑:

bool volatile push(struct Data element);

声明一个 non-volatile 成员函数,它返回一个 bool volatile (= volatile bool)。你要

bool push(struct Data element) volatile;

关于c++ - 定义 volatile 类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3078237/

相关文章:

java - JLabel setText()方法据说是线程安全的,但是它能保证可见性吗

c# - volatile 字段 : How can I actually get the latest written value to a field?

java, volatile 静态和同步 - 线程中的空异常

C++ 从 .txt 读取文件并使用 Xcode 在新的 .txt 中保存所需的值

c++ - isalpha() 函数不适用于字符串中的空格

c++ - 将临时对象绑定(bind)到 const 引用

c# - volatile 关键字可以用于构建线程安全的自动清除缓存吗?

c++ - 将 Mat 转换为 vector <float> 并将 Vector<float> 转换为 opencv 中的 mat

c++ - C++ 协方差何时是最佳解决方案?

c - 当仅在中断期间读取变量时是否需要 volatile