When you exit the function, all local variables are destroyed. By returning a link to tmp , you return a link to an object that soon ceases to exist (that is, technically, the address of a memory region whose contents no longer make sense).
Access to such a dangling link causes what is called "w90 behavior", and, unfortunately, "work as usual" is one of the undefined behaviors. What can happen here is that std::string stores a small static buffer for small strings (unlike large strings for which it grabs memory from the heap), and after getString exits, the stack space occupied by this string is not reset so it still works.
If you try to build debugging or call another function between them (which will effectively overwrite the stack space), it will no longer work.
Alexander Gessler
source share