thomas wrote:
-----code----
vector<int&calc(){
vector<inttemp;
temp.push_back(3);
return temp;
}
----code----
"temp" is a temporary variable, when returned, it's like return by
alias.
So is the code above legal?
If you mean "legal" as in "compiles", then the answer is yes. If you
mean "legal" as in "works", the answer is no.
Returning a reference to a temporary is basically no different than
returning a pointer to a temporary. In either case if you try to access
the pointed object, bad things will happen.
To do what you want you have several options. To do *exactly* what you
are wanting to do above, either return by value (instead of by
reference), or return a dynamically allocated instance (preferably using
a smart pointer or std::auto_ptr).
In the larger context other solutions may be better.