There are multiple ways of making a method. I'm not quite sure when to use const and reference in method parameters.
Imagine a method called 'getSum' that returns the sum of two integers. The parameters in such a method can have multiple forms.
int getSum1(int, int);
int getSum2(int&, int&);
int getSum3(const int, const int);
int getSum4(const int&, const int&);
Correct me if I'm wrong, but here's how I see these methods:
getSum1
- Copies integers and calculatesgetSum2
- Doesn't copy integers, but uses the values directly from memory and calculatesgetSum3
- Promises that the values won't changegetSum4
- Promises that the values won't change & doesn't copy the integers, but uses the values directly from memory
So here are some questions:
So is
getSum2
faster thangetSum1
since it doesn't copy the integers, but uses them directly?Since the values aren't changed, I don't think 'const' makes any difference in this situation, but should it still be there for const correctness?
Would it be the same with doubles?
Should a reference only be used with very large parameters? e.g. if I were to give it a whole class, then it would make no sense to copy the whole thing