简体   繁体   English

垃圾记忆?

[英]Garbage memory?

I was just going through an article which explains about Wild pointers. 我刚刚阅读了一篇解释Wild指针的文章。 For garbage memory, it states that when a pointer pointing to a memory object is lost, ie it indicates that the memory item continues to exits, but the pointer to it is lost; 对于垃圾内存,它指出当指向内存对象的指针丢失时,即它指示内存项继续退出,但指向它的指针丢失; it happens when memory is not released explicitly. 当内存未明确释放时会发生。 I was trying to understand this with an example. 我试图通过一个例子来理解这一点。 Here is what I wrote 这是我写的

#include <iostream>

using namespace std;
int q =12;
int point()
{
   int *p;
   p = &q;
   //delete p;
}
int main()
{
   point();
   return 0;
}

So, in the above example, memory item (q) continues to exist, but the pointer to it is lost. 因此,在上面的例子中,内存项(q)继续存在,但是指向它的指针丢失了。 I may have misunderstood it all wrong, but if I understood it correctly, then does this example addresses 'garbage memory' definition given above? 我可能误解了一切都错了,但如果我理解正确,那么这个例子是否解决了上面给出的“垃圾记忆”定义? If yes, then I should use delete p, right? 如果是,那么我应该使用delete p,对吗?

C++ Does not have garbage collection the way you understand it.. But what you are showing is not a "memory leak" which is what I think you mean. C ++没有你理解它的方式进行垃圾收集..但你所展示的不是“内存泄漏” ,这就是我认为你的意思。

In this case you are pointing to a memory location that is NOT dynamically allocated , and is accessible from outside the function for the duration of the program. 在这种情况下,您指向的是未动态分配的内存位置,并且可以在程序持续时间内从函数外部访问。


int point()
{
   int *p = new int();
   //delete p;
}

This is now a memory leak , since the memory is still allocated, but noone can access it any more. 这是一个内存泄漏 ,因为仍然分配了内存,但没有人可以再访问它。 If this were Java or any other language which supports GC, this memory would now be queued to be Garbage collected . 如果这是Java或任何其他支持GC的语言,则此内存现在将排队等待收集垃圾


The recommended style in C++ is to make all allocated memory auto deallocate themselves , as far as possible, with a concept called Resource Acquisition Is Initialization (RAII) , using smart pointers as below. C ++中推荐的样式是使用智能指针 (如下所示 使所有已分配的内存尽可能自动解除分配 ,称为资源获取初始化(RAII)

int point()
{
   std::unique_ptr<int> p(new int());
   //delete p;  // not needed.
}

When the variable p is destroyed, at the end of its scope, it will automatically call delete on the allocated memory so you dont have to. 当变量p被销毁时,在其范围的末尾,它将自动调用已分配内存上的delete ,因此您不必这样做。 By making stuff clean up after themselves, we enable the below. 通过自己清理东西,我们启用下面的功能。

C++ is my favorite garbage collected language because it generates so little garbage C ++是我最喜欢的垃圾收集语言,因为它产生的垃圾很少

Bjarne Stroustrup's FAQ: Did you really say that?. Bjarne Stroustrup的常见问题解答:你真的这么说吗? Retrieved on 2007-11-15. 检索2007-11-15。 http://en.wikiquote.org/wiki/Bjarne_Stroustrup http://en.wikiquote.org/wiki/Bjarne_Stroustrup

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

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