I\'m reading Accelerated C++ and in Chapter 4 they bring up the concept of lvalu
ID: 654264 • Letter: I
Question
I'm reading Accelerated C++ and in Chapter 4 they bring up the concept of lvalues. There's an example of something that shouldn't work, but after trying it myself I found that it does indeed work.
Specifically they state that, given these functions:
// return an empty vector
vector<double> emptyvec()
{
vector<double> v;
return v;
}
// read things from an input stream into a vector<double>
// (I'm leaving out the function body here because it's irrelevant)
istream &read_things(istream& in, vector<double>& hw);
This should not be allowed:
read_stuff( cin, emptyvec() );
Because emptyvec() is an expression and returns a temporary object (a non-lvalue as they called it in the book). However, this not only compiles but actually runs (Windows 7/VisualStudio 2010).
So, what's going on? Was this just a bad example on the authors' part, or is there something else happening that I don't understand.
Thanks.
Explanation / Answer
The concern the book mentions would come into play if the function was declared as:
vector<double> &emptyvec()
or
vector<double> *emptyvec()
as it would then be returning a temporary value by reference, and by the time you used the reference, the value it referred to would be gone. Your compiler should issue a warning or an error for this case, and you might (but might not) see a variety of possible failures at run time (sadly, the type of error you would see could vary widely).
On the other hand, if the function is indeed declared as
vector<double> emptyvec()
the vector is being returned by value (i.e. a copy of the actual vector is being made into wherever you store the return value), and the program should work correctly.