Returning reference to a local variable

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

    The temporary object is deallocated, however its contents are still there on the stack, until something rewrites it. Try to call a few functions between calling your function and printing out the returned object:

    const string& garbage = getString("Hello World!");
    callSomeFunctionThatUsesALotOfStackMemory();
    cout<< garbage << endl;
    
    0 讨论(0)
提交回复
热议问题