I hardly see problems with your code. The origin of the error seems to be in a different place.
I assume that you will return the local variable reference.
See my example:
#include <iostream> using std::string; const string& getString() { string text("abc"); return text; } int main() { string text("abc"); std::cout << (getString() == text ? "True" : "False") << "\n"; return 0; };
Output on my machine:
False
However, in some environments I experienced an exception. This code is not valid, but the behavior is undefined. Apparently, it often works correctly.
Watch for compilation warnings, for example:
a.cpp:7: warning: reference to local variable 'text' returned
You can also try compiling your code with the -Wall option and see if any real problems are being warned.
source share