C++ Pass By Const Reference and Return By Const Reference

后端 未结 5 1122
感动是毒
感动是毒 2021-01-11 18:23

I\'m trying to understand if there is any benefit to returning a const reference. I have a factorial function that normally looks like this:

uns         


        
5条回答
  •  余生分开走
    2021-01-11 19:00

    A const reference isn't faster than a value, if the size of the value is small. In this case the type of the value is long, which is IMO small (e.g. 4 to 8 bytes): so a const reference will be no faster. In fact it may be slower, because to get the value of a reference the compiler may need to emit the code that will dereference the reference (like dereferencing a pointer).

    Given that a reference is implemented (internally) like a pointer, I'd expect to get better performance from passing references than from passing values when the size of the value is bigger than the size of a pointer (assuming that it's even legal to pass a reference: a reference to a local variable that's gone out of scope isn't legal).

提交回复
热议问题