简体   繁体   English

在C ++中使用非volatile对象调用volatile成员函数

[英]Calling volatile member function using not volatile object in C++

What happens, If calling volatile member function using not volatile object ? 如果使用非volatile对象调用volatile成员函数会发生什么?

#include <iostream>
using namespace std;

class A 
{
private:
    int x;
public:
    void func(int a) volatile //volatile function
    {
        x = a;
        cout<<x<<endl;
    }
};

int main() 
{
    A a1; // non volatile object
    a1.func(10);
    return 0;
}

The rule is same as const member function. 该规则与const成员函数相同。 A volatile member function could be called on a non- volatile object, but a non- volatile member function couldn't be called on a volatile object. 可以在非易失volatile对象上调用volatile成员函数,但是不能在volatile对象上调用非易失volatile成员函数。

For your case, A::func() will be invoked fine. 对于你的情况, A::func()将被调用。 If you make them opposite, the compilation would fail. 如果使它们相反,则编译将失败。

class A 
{
private:
    int x;
public:
    void func(int a) // non-volatile member function
    {
        x = a;
        cout<<x<<endl;
    }
};

int main() 
{
    volatile A a1;   // volatile object
    a1.func(10);     // fail
    return 0;
}

You can call it just like a const function on a non-const object, but for different reasons. 您可以像非const对象上的const函数一样调用它,但原因各不相同。

The volatile qualifier makes the implicit this parameter be treated as a pointer to a volatile object. volatile限定符使隐式this参数被视为指向volatile对象的指针。

Essentially, this means that the semantics of volatile objects will be applied when accessing the data member(s) of the object. 实质上,这意味着在访问对象的数据成员时将应用易失性对象的语义。 Any read of x cannot be optimized away, even if the compiler can prove there is no recent write after the last read. 即使编译器可以证明在最后一次读取之后没有最近的写入,也无法对x任何读取进行优化。

Naturally, if the object isn't really volatile the body of func is still correct, albeit not as optimized as it can be. 当然,如果对象不是真正易变的,那么func的主体仍然是正确的,尽管没有尽可能优化。 So you can call it just fine. 所以你可以称它为好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM