What happens in C++ when I pass an object by reference and it goes out of scope?

前端 未结 5 1229
忘了有多久
忘了有多久 2020-12-06 18:08

I think this question is best asked with a small code snippet I just wrote:

#include 

using namespace std;

class BasicClass
{
public:
    B         


        
5条回答
  •  失恋的感觉
    2020-12-06 18:46

    Undefined behavior. By definition you cannot make assumptions about what will happen when that code runs. The compiler may not be clearing out the memory where bc resides yet, but you can't count on it.

    I actually fixed the same bug in a program at work once. When using Intel's compiler the variable which had gone out of scope had not been "cleaned up" yet, so the memory was still "valid" (but the behavior was undefined). Microsoft's compiler however cleaned it up more aggressively and the bug was obvious.

提交回复
热议问题