【问题标题】:Calling volatile member function using not volatile object in C++在 C++ 中使用非 volatile 对象调用 volatile 成员函数
【发布时间】:2018-01-08 05:12:50
【问题描述】:

如果使用非易失性对象调用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;
}

【问题讨论】:

  • 会正常调用。
  • 很好的措辞可以避免 thisthisthis 完全是骗子。

标签: c++ c++11 volatile member-functions


【解决方案1】:

规则同const成员函数。可以对非volatile 对象调用volatile 成员函数,但不能对volatile 对象调用非volatile 成员函数。

对于您的情况,A::func() 将被正常调用。如果你让它们相反,编译会失败。

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;
}

【讨论】:

    【解决方案2】:

    您可以像在非常量对象上调用 const 函数一样调用它,但是出于不同的原因。

    volatile 限定符使隐式 this 参数被视为指向 volatile 对象的指针。

    本质上,这意味着在访问对象的数据成员时将应用易失性对象的语义。任何对x 的读取都不能被优化掉,即使编译器可以证明在最后一次读取之后没有最近的写入。

    当然,如果对象不是真正易变的,func 的主体仍然是正确的,尽管没有尽可能优化。所以你可以这么称呼它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多