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.
emptyvec()? As given (vector<double> vector) it doesn't make much sense. Was thisvector<double> &in the book (in which case the code is indeed an example of the problem the book mentions)? – jimwise Jan 24 at 15:47vector<double>orvector<double> &? – jimwise Jan 24 at 16:09vector<double> vector emptyvec()which is not valid syntax) I don't have the book here at the moment, but when I tried changing it fromvector<double>tovector<double>&the compiler threw an error: warning C4172: returning address of local variable or temporary So that seems to be more in line with what the author was saying. – Alex Jan 24 at 16:12