What are the benefits to passing integral types by const ref

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

    well the cost of a reference is the same typically of that of an integral type, but with the reference you have an indirection that has to take place, because the reference to some memory has to be resolved into a value.

    Just copy by value, stick to an immutable convention for built-in types.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-05 22:55

    Please read Want Speed? Pass by Value by Dave Abrahams.

    0 讨论(0)
  • 2021-02-05 22:56

    You can use boost::call_traits<your type>::param_type for optimal parameter passing. Which defaults to simple parameter passing of primitive types and passing by const reference of structs and classes.

    0 讨论(0)
  • 2021-02-05 23:02

    It's usually not worth it. Even for inline function, the compiler won't be stupid. The only time I would say it's appropriate is if you had a template; it might not be worth the extra effort to specialize for builtins just to take a copy instead of a reference.

    0 讨论(0)
  • 2021-02-05 23:02

    When writing or using templates, you may end up with (const int &) because the template writer can't know what the type actually is. If the object is heavyweight, passing a reference is the right thing to do; if it's an int or something, the compiler may be able to optimize it away.

    In the absence of some kind of external requirement, there is generally no reason to do something like this for a one-off function -- it's just extra typing, plus throwing around references actually tends to inhibit optimization. Copying small data in registers is much cheaper than reloading it from memory in case it's changed!

    0 讨论(0)
提交回复
热议问题