【问题标题】:What is the register cache and what does it have to do with const variables?什么是寄存器缓存,它与 const 变量有什么关系?
【发布时间】:2011-09-14 19:02:07
【问题描述】:

来自http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.14

即使语言禁止const_cast,避免在const 成员函数调用中刷新寄存器缓存的唯一方法是解决别名问题(即证明不存在非const指向对象的指针)。

什么是寄存器缓存,在const 成员函数调用中刷新它是什么意思?

【问题讨论】:

    标签: c++ constants compiler-optimization cpu-registers pointer-aliasing


    【解决方案1】:

    我认为它在谈论这样的事情:

    class A;
    
    class B {
    public:
        A * m_a;
        B(A * a) : m_a(a) {}
    }; 
    
    Class A {
    public:
        int m_num;
        A(int num=0) : m_num(num) {}
        void DoSomethingConst(B * someB) const;
    };
    
    void SomeOtherFunction()
    {
       A myA;
       B myB(&myA);
    
       //do something with myA.m_num (1)
       myA.DoSomethingConst(&myB);
       //do something else with myA.m_num (2)
    }
    

    SomeOtherFunction 内部,编译器无法在(1)期间将myA.m_num 的值保存在寄存器中并在(2)期间再次使用它。即使DoSomethingConstconst 并且因此不应更改myA.m_num 的值,该值仍然可以更改,因为myB 内部有一个指向myA 的非常量指针,因此myA.m_num 可以在myA.DoSomethingConst 期间仍然会发生变化。在这种情况下,证明存在对myA 的非常量引用是微不足道的,在一般情况下它不是。

    【讨论】:

      【解决方案2】:

      这里的“寄存器缓存”是指让编译器将值存储在寄存器中。

      调用const 成员函数不应更改任何成员变量的值,因此如果其中一些存储在寄存器中,这些值在函数返回时仍然有效。

      我猜这不是一个非常重要的优化。

      【讨论】:

        猜你喜欢
        • 2017-06-15
        • 2017-05-18
        • 2011-02-02
        • 1970-01-01
        • 2011-03-28
        • 2019-07-22
        • 2012-03-12
        • 2012-01-11
        • 1970-01-01
        相关资源
        最近更新 更多