There are five main cases where you should use pass-by-reference over pass-by-value:
- If you are calling a function that needs to modify its arguments, use pass-by-reference as its the only way to get this effect (I treat pass-by-reference and pass-by-pointer interchangeably in this case, though with pass-by-pointer you often have to explicitly check for
nullptr
.)
- If you're calling a function that needs to take a large object as a parameter, pass it by const reference to avoid making an unnecessary copy of that object and taking a large efficiency hit.
- If you're writing a copy or move constructor which by definition must take a reference, use pass by reference.
- If you're writing a function that wants to operate on a polymorphic class, use pass by reference or pass by pointer to avoid slicing.
- If you're writing a function that might return a very large or uncopyable object, use pass by reference as a way to use a parameter to store the produced value.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…