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

后端 未结 5 1082
感动是毒
感动是毒 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:16

    The const reference is incorrect here - you're returning a reference to a local variable - an un-named temporary here, either 1 or the result of n * factorial(n - 1). Because the reference is to a local variable in the function, by the time the reference gets to the caller, that local variable has already gone out of scope, and is invalid.

    Return a const reference to large structured types that you want to avoid a copy to when the reference will survive the exit of the function. Usually, this means returning a reference to an argument or to a member variable (in the case of classes).

提交回复
热议问题