Tag: Reference value Pass reference pass
In C + +, the parameters of a function are passed by value, and address is passed. The pass-through address has pointers and reference methods.
In the function arguments, the reason for the address is:
1. Enable the modulated function to modify the data object in the keynote function;
2. Address can reduce the data copy, improve program execution speed.
So, when to use value delivery, when to use address delivery (pointers and references)?
Here are some of the things you might encounter when writing code
The data object is not modified when the function is being tuned using a Parameter object
- If the data object to pass in the function is small, such as a built-in data type or a small-scale struct, then the value is passed;
- If the data object is an array, use the pointer (which is also your only option). The pointer adds a const modifier;
- If the data object is a large-scale struct, use a const pointer or a const reference;
- If the data object is a class object, use a const reference. This is also the standard practice of passing class objects in C + +;
The data object is modified when the function uses a Parameter object
- The data object is the built-in data type, using the pointer (func (&VAR) to indicate that Var is to be modified in the function, which is better readable than the invocation form func (VAR) using the reference;
- The data object is an array, and the pointer is the only choice;
- A data object is a struct, using pointers or references;
- The data object is a class object, using References;
Of course, these are just general conditions. Special cases are discussed additionally.
Parameter passing (reference, pointer, value pass) c++11