I'm trying to understand exact C++ (pre C++0x) behavior with regards to references and rvalues. Is the following valid?
void someFunc ( const MyType & val ) {
//do a lot of stuff
doSthWithValue ( val);
}
MyType creatorFunc ( ) {
return MyType ( "some initialization value" );
}
int main () {
someFunc ( creatorFunc() );
return 0;
}
I found similar code in a library I'm trying to modify. I found out the code crashes under Visual Studio 2005.
The way I understand the above, what is happening is:
creatorFunc is returning by value, so a temporary MyType object obj1 is created. (and kept... on the stack?)
someFunc is taking a reference to that temporary object, and as computation progresses the temporary object is overwritten/freed.
Now, what is mind-boggling is that the code most often works fine. What is more, with a simple piece of code I cannot reproduce the crash.
What is happening/supposed to happen here? Does is matter if the reference (val) is const or not? What is the lifespan of the object returned from creatorFunc?