Returning reference to a local variable

前端 未结 7 1247
忘掉有多难
忘掉有多难 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:29

    Are you sure? It should segfault (it will with gcc on most platforms). That code does contain an error, and if you get 'lucky' and it works, then you're brushing a nasty bug under the carpet.

    Your string is returned by reference, that is, rather than making a new string which is valid in the context you are returning into, a pointer to a stale, destructed, object is being returned, which is bad. const string getString... will do as the declaration for the function's return type.

提交回复
热议问题