< Previous | Contents | Next >
Assigning a Returned Reference to a Variable
Next I assign a returned reference to a variable.
string str = refToElement(inventory, 2);
The preceding code doesn’t assign a reference to str. It can’t, because str is a string object. Instead, the code copies the element to which the returned reference refers (the element in position 2 of inventory) and assigns that new copy of the string object to str. Because this kind of assignment involves copying an object, it’s more expensive than assigning one reference to another. Sometimes the cost of copying an object this way is perfectly acceptable, but you should be aware of the extra overhead associated with this kind of assignment and avoid it when necessary.
Next I send the new string object, str, to cout, and shield is displayed.