简体   繁体   English

C ++对象泄漏

[英]C++ object leak

I am currently learning C++, and I'm experiencing with local scope of objects. 我目前正在学习C ++,并且正在体验对象的局部范围。

If I understand correctly, with this code : 如果我正确理解,请使用以下代码:

void stepOne() {
TestClass t1;
t1.thisIsAInt = 2;}

Once we exit the scope of the stepOne method, the t1 object should be cleared out of memory. 一旦退出stepOne方法的范围,就应该将t1对象清除出内存。

Now, I wanted to test this, so with a debugger I got the address of the object, and once I got back into main , I made a pointer on the address that I got from the debugger. 现在,我想测试一下,因此使用调试器,我得到了对象的地址,回到main ,我在从调试器得到的地址上建立了一个指针。

I was surprised to find that the pointer was still pointing to the same object I created earlier. 我惊讶地发现指针仍然指向我之前创建的同一对象。

Normally, it is my understanding that the object would have been cleared of memory since we left the scope. 通常,据我了解,自从我们离开示波器以来,该对象将被清除内存。

Now, 现在,

  • Do I not understand it properly? 我是否理解不正确?
  • Did getting the address of it made it not leave the scope? 获取地址是否使它不离开范围?
  • Is it free memory for the OS, and just not cleared yet? 它是OS的可用内存,并且尚未清除吗? (Filled with zeroes) (用零填充)
  • If I passed the pointer to a function from stepOne, would it still have been cleared once I left the scope? 如果我将指针从stepOne传递给函数,那么一旦离开示波器,是否仍将其清除? ( I understand I could have used a smart pointer, to make sure it only survives the local scope) (我知道我可以使用一个智能指针,以确保它只能在本地范围内生存)

Once an object has gone out of scope and is destructed (add a breakpoint in the destructor to make sure it is) you should not reference the memory that was owned by that object. 一旦对象超出范围并被销毁(在析构函数中添加断点以确保已断点),则不应引用该对象拥有的内存。

Just because the object is destructed doesn't mean the memory it occupied will just "disappear". 仅仅因为对象被破坏并不意味着它所占用的内存只会“消失”。 The memory still exists, and until it is reused by another object will not change its contents. 内存仍然存在,并且在被另一个对象重用之前不会更改其内容。 Clearing memory takes (a little) time, doing it perhaps thousands of times each second will suddenly become very expensive. 清除内存需要(一点)时间,每秒执行数千次可能会突然变得非常昂贵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM