Returning reference to a local variable

前端 未结 7 1256
忘掉有多难
忘掉有多难 2020-12-18 14:04

Why can this code run successfully in Code::block. The IDB just reports

warning: \"reference to local variable ‘tmp’ returned\",

7条回答
  •  忘掉有多难
    2020-12-18 14:39

    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.

提交回复
热议问题