Upon leaving a function, all local variables are destroyed. By returning a reference to tmp
, you are returning a reference to an object that soon ceases to exist (that is, technically, the address of a memory region whose contents are no longer meaningful).
Accessing such a dangling reference invokes what is called 'undefined behaviour' - and sadly, 'work as usual' is one kind of 'undefined behaviour'. What might happen here is that std::string
keeps a small static buffer for small strings (as opposed to large strings, for which it grabs memory from the heap), and upon leaving getString
the stack space occupied by this string is not zeroed so it still seems to work.
If you try a debug build, or invoke another function in between (which will effectively overwrite the stack space), it won't work anymore.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…