What are the benefits to passing integral types by const ref

前端 未结 12 1818
情话喂你
情话喂你 2021-02-05 22:18

The question: Is there benefit to passing an integral type by const reference as opposed to simply by value.

ie.

void foo(const int& n); // case #1
<         


        
12条回答
  •  臣服心动
    2021-02-05 22:49

    It's not only performance. A true story: this week I noticed that a colleague tried to improve upon the Numerical Recipes and replaced the macro

    
        #define SHFT(a,b,c,d) do { (a)=(b); (b)=(c); (c)=(d); } while (0)
    

    by this function

    
        inline void Rotate(double& dFirst, double& dSecond, double& dThird, const double dNewValue)
        {
            dFirst = dSecond;
            dSecond = dThird;
            dThird = dNewValue;
        }   // Function Rotate
    

    This would have worked, if he had passed the last parameter by reference, but as it is, this code

     
            Rotate(dum,*fb,*fa,dum);
    

    which was supposed to swap *fa and *fb no longer works. Passing it by reference without const is not possible, as in other places non-l-values are passed to the last parameter.

提交回复
热议问题