< Previous | Contents | Next >
Assigning to a Variable the Value Pointed
Next I assign the value pointed to by a returned pointer to a variable.
string str = *(ptrToElement(&inventory, 2));
The call to prtToElement() returns a pointer to inventory[2]. However, the preceding statement doesn’t assign this pointer to str—it can’t because str is a string object. Instead, the computer quietly makes a copy of the string object to which the pointer points and assigns that object to str. To help drive this point home, check out Figure 7.6, which provides an abstract representation of the results of this assignment.
str is a new string object, totally independent from inventory.
An assignment like this one, where an object is copied, is more expensive than the assignment of one pointer to another. Sometimes the cost of copying an object is perfectly acceptable, but you should be aware of the extra overhead associated with this kind of assignment and avoid it when necessary.