Should I pass values โ€‹โ€‹of "simple" types by reference?

Consider the following:

int increment1 (const int & x)
{ return x+1; }

int increment2 (const int x)
{ return x+1; }

      

I understand that passing references to class objects is like this, but I'm wondering if it's worth passing a reference to simple types? What is more optimal? Pass by reference or pass by value (in case of type simle?)

+2


source to share


4 answers


Unless you want invocation by reference semantics, that is, you want to access the actual variable in the invoked invocation, you should not use invocation by reference for simple types.



For a similar more general discussion, see: "const T & arg" vs. "T arg"

+6


source


Do you also understand premature optimization ? :)

Make it clearer. If the function returns a value, it doesn't need a reference. In this case, the reader (human!) Of the Code may wonder why the link is being used without a valid reason.

UPDATE: If you want a function to be called increment()

, that (to me) implies that it should change the value of the passed value and not return it. It sounds like a change at the site of surgery. Then it might make sense to use a reference (or pointer) and remove the return value:



void increment(int &value)
{
  ++value;
}

      

If you research which is faster, I still think that you are optimizing prematurely.

+6


source


It may not be "worth it," but sometimes it is different. Consider the following functions:

int const* addr_ref    (int const& i)  { return &i; }
int const* addr_byvalue(int const  i)  { return &i; }

      

They obviously return different values. Therefore, it is sometimes useful.

In the meantime, you must stick to your coding rule. Most likely, compiler optimizations within the function will discard unnecessary dereferencing, and the caller's code also uses a reference, so performance is unlikely to be an issue here.

0


source


If the functions are templates, you have a harder choice to make. Should T be accepted by value or by const reference when you don't know how big or expensive the copy of T is?

In this case, I would rather pass a const reference. If the size of T is less than or equal to the size of the reference, it is possible that the compiler will perform the optimization: it just passes the parameter by value anyway, since the reference parameter const promises should not change the parameter, so the side effects are the same. However, the compiler may also fail to do this optimization, especially if it is having development issues if there are any const_casts associated with it.

But for this reason, I would be in favor of const-reference passing - perhaps, but not sure if a smart compiler can choose the correct transfer method for you, depending on the type size and architecture.

0


source







All Articles