返回语句(return)

1、Returning a Nonreference Type

The value returned by a function is used to initialize a temporary object created at the point at which the call was made. A temporary object is an unnamed object created by the compiler when it needs a place to store a result from evaluating an expression. C++ programmers usually use the term "temporary" as an abreviation of "temporary object."

The temporary is initialized by the value returned by a function in much the same way that parameters are initialized by their arguments. If the return type is not a reference, then the return value is copied into the temporary at the call site. The value returned when a function returns a nonreference type can be a local object or the result of evaluating an expression.

As an example, we might want to write a function that, given a counter, a word, and an ending, gives us back the plural version of the word if the counter is greater than one:

// return plural version of word if ctr isn't 1
string make_plural(size_t ctr, const string &word,
const string &ending)
{
    return (ctr == 1) ? word : word + ending;
}    

This function either returns a copy of its parameter named word or it returns an unnamed temporary string that results from adding word and ending . In either case, the return copies that string to the call site.

2、Returning a Reference Type

When a function returns a reference type, the return value is not copied. 

3、Never Return a Reference to a Local Object.

4、Reference Returns Are Lvalues

A function that returns a reference returns an lvalue. That function, therefore, can be used wherever an lvalue is required:

char &get_val(string &str, string::size_type ix)
{
    return str[ix];
}
int main()
{
    string s("a value");
    cout << s << endl; // prints a value
    get_val(s, 0) = 'A'; // changes s[0] to A
    cout << s << endl; // prints A value
    return 0;
}

It may be surprising to assign to the return of a function, but the return is a reference. As such, it is just a synonym for the element returned.
If we do not want the reference return to be modifiable, the return value should be declared as const .

posted on 2014-04-23 16:38  江在路上2  阅读(266)  评论(0)    收藏  举报