What are the benefits to passing integral types by const ref

前端 未结 12 1989
情话喂你
情话喂你 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:55

    It depends on the compiler, but I'd expect that any reasonable optimizer would give you the same results either way.

    I tested with gcc, and the results were indeed the same. here's the code I tested:

    inline int foo(const int& n) {
      return n * 2;
    }
    
    int bar(int x) {
      int y = foo(x);
      return y;
    }
    

    (with and without const & on foo's n parameter)

    I then compiled with gcc 4.0.1 with the following command line:

    g++ -O3 -S -o foo.s foo.cc
    

    The outputs of the two compiles were identical.

提交回复
热议问题