Returning values by reference

Hello. I am currently learning about stacks in C++ and I was wondering why I was recommended to return values by reference, instead of returning a value by a string. Can you explain why it's recommended? Thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <stack>

using namespace std;

int main()
{
	
	stack<string> names;
	
	names.push("James");
	names.push("Ken");
	names.push("Wong");
	
	while (names.size() > 0)
	{
		string &test/* Why include a reference before "test"? */ = names.top();
		cout << test << endl;
		names.pop();
	}
	
	return 0;
}
top() returns a reference to the topmost element in the stack. If you didn't use & when defining test you would create a new string object that is a copy of the string that top() returns a reference to. Creating a copy is extra work, especially if the string is long, so that is why you make it a reference.

Note that since test is a reference to an element in the stack you need to be careful not using it after the element has been removed from the stack. Switching the order of line 18 and 19 would be a mistake for this reason.
Last edited on
Another, smaller, benefit is that it lets you change the value at the stop of the stack without having to pop it and push the new value:
1
2
string &test = names.top();
test = "new value";    // poof!  Now the top of stack has changed to "new value" 
Topic archived. No new replies allowed.