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.
I have a function where I have to modifiy the values of a vector.
is it a good practice in C++ to return the vector?
Function 1:
vector<string> RemoveSpecialCharacters(vector<string> words)
{
for (vector<string&…
If I have a function which takes a pointer to an integer, and I pass a reference to an integer variable from my main, is this call by value or call by reference? Sample code:
#include <iostream>
using …