e.g. Person(const string & aName){...}
Would a program use up a significant amount of memory just because we don't pass by reference? I know how to use const-reference but am having trouble understanding why I'm using them.
e.g. Person(const string & aName){...}
Would a program use up a significant amount of memory just because we don't pass by reference? I know how to use const-reference but am having trouble understanding why I'm using them.
Would a program use up a significant amount of memory just because we don't pass by reference?
A copy of the string (that would be made if you passed the parameter by value [unless the call is expanded inline, in which case it matters not how the parameter is passed]) would use as much memory as the original string. Thus such program would use twice as much memory for the string and its copy as another program would use for the one string that wasn't copied.
The difference is not limited to the amount of used memory. Copying memory takes more time than not copying memory. The overhead from passing by reference is constant both by speed and memory use, while the overhead of copying a string increases linearly as the length of the string increases.
The linear complexity of copying the string can be significant if the string is not guaranteed to be small. Even if the string is small, the allocation overhead can be significant if the function is called often.
What is the significance of passing const-reference parameters?
When you use a const reference rather than non-const, it will be easier to reason about the correctness of your program, since you implicitly know just by the declaration of the function, that it will not modify the referred object. It also allows you to pass const objects, and temporaries to the function.
Passing by values has those same advantages, but it requires a copy which can have significant performance impact as I explained in earlier paragraph. If the function itself would make a copy of the string anyway, then it may be better to pass by value, so that the copy is apparent to the reader.