What are the benefits to passing integral types by const ref

前端 未结 12 1828
情话喂你
情话喂你 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条回答
  •  梦毁少年i
    2021-02-05 22:54

    A lot of people are saying there's no difference between the two. I can see one (perhaps contrived) case in which the difference would matter...

    int i = 0;
    
    void f(const int &j)
    {
        i++;
    
        if (j == 0)
        {        
            // Do something.
        }
    }
    
    void g()
    {
        f(i);
    }
    

    But.. As others have mentioned... integers and pointers are likely to be of similar size. For something as small as an integer, references will decrease your performance. It probably won't be too noticeable unless your method is called a lot, but it will be there. On the other hand, under some circumstances the compiler may optimize it out.

提交回复
热议问题