MSVC is accepting this snippet
#include <iostream>
#include <string>
#include <vector>
std::string retstr() {
return std::string("HelloWorld");
}
void callFunc(std::string& ref) {
std::cout << ref;
}
int main()
{
callFunc(retstr());
}
for some backward compatibility reason.
Now.. I'm getting some crashes in a DLL in a function which works exactly like this snippet above: the compiler didn't warn me of having a lvalue reference binding to a ret-by-value thingy.
My question is: this is probably not standard but could it cause a program crash (access violation to be precise)?
The code as written is fine regarding lifetimes, since the temporary value
retstr()
lives until the end of the full-expression, so it lives as long as the function call.The fact that MSVC allows binding a lvalue reference to an rvalue does not change that. As always, you have to make sure that
callFunc
does not store references into the string beyond the duration of the function call.Binding non constant reference to "rvalue" should definitely be flagged by the compiler .However if compiler is not flagging it ( as in your case ) , it would be problematic at run time(may crash also) .
In your example temporary is being reference which unfortunately was not flagged by the compiler .Now , when this reference (ref) is utilized , it may crash as it is pointing to something which lost .
I would like to share few points which may be useful .