Explore more and find the answer to determine how to pass in old post (sorry for duplicate)
- If the function intends to change the argument as a side effect, take it by non-const reference.
- If the function doesn't modify its argument and the argument is of primitive type, take it by value.
- Otherwise take it by const reference, except in the following cases
- If the function would then need to make a copy of the const reference anyway, take it by value.
[Original Post is Below]
I'd like to summarize the use of passing by value, const value, reference, const reference, pointer, const pointer and please correct me and give me your suggestions.
- As for reference and pointer, use const if possible (thanks to all).
- There is no performance difference between passing by reference and pointer.
- When the size is not larger than a pointer (thanks to Mark Ransom), pass by value.
And some questions:
- I seldom see passing by const value. Is it useful or the compiler will detect the const-ness in passing by value?
- The const reference takes too much space. Can I just use passing by value? Will the modern compilers optimize it to not sacrifice the performance?
According the the article "Want Speed? Pass by Value" juanchopanza mentioned, I add one more item.
- If you will copy your arguments, pass them by value and let the compiler do the copying other than passing them by const reference and doing the copy by yourself in the function body.
Thanks a lot!