Returning reference to a local variable

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

    C++ standard tells that binding a temporary object to a const reference extends the lifetime of the temporary to the lifetime of the reference itself. So the code should work on any standard-compliant compiler, but the practice itself is not really nice in my view.

    If you do use your string a currently unused in your example as string a = getString("Hello World!") you would simply make a copy, and in case of const string& a = getString("Hello World!") my bet that you should never have your temporary garbaged.

提交回复
热议问题