Explore more and find the answer to determine how to pass in old post (sorry for duplicate)
[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.
And some questions:
According the the article "Want Speed? Pass by Value" juanchopanza mentioned, I add one more item.
Thanks a lot!
I seldom see passing by const value. Is it useful or the compiler will detect the const-ness in passing by value?
Passing by const
value doesn't really exist. When you pass by value, you can't modify the value in such a way that the changes will be visible outside of the subroutine. This is because when you pass by value, a copy is made of the original value and that copy is used in the function.
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?
Passing by (const
) reference is not the same as passing by value. When you pass by reference the value is NOT copied, a memory location is simply supplied and thus you may 'modify' (indirectly) the value that you pass by reference.
Take for example, the following:
void byValue(int x) {
x += 1
}
void byRef(int &x) {
x += 1
}
// ...
{
y = 10;
byValue(y);
cout << y << endl // Prints 10
byRef(y);
cout << y << endl; // Prints 11
}
// ...
Use const as much as possible.
Passing const
where necessary is always a good idea. It helps code readability, lets others know what will happen to the values they pass to the method, and helps the compiler catch any mistakes you may make in modifying the value inside the method.
There is no performance difference between passing by reference and pointer.
A negligible amount, if any. The compiler will take care of the details here. It saves you the effort of creating a pointer, and it nicely dereferences it for you.
When the size is not larger than a word, pass by value.
As Mark points out, you do this if the value is smaller than a pointer. Pointers are different sizes on 32bit and 64bit systems (hence the name) and so this is really at your discretion. I'm a fan of passing pointers for nearly everything except the primitive types (char
, int8_t
, int16_t
, float
, etc), but that is just my opinion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With