开发者

About Garbage collection in C++

开发者 https://www.devze.com 2023-03-14 03:32 出处:网络
I am reading about the Garbage Collector pattern. It was mentioned that this architectural pattern removes the vast majority of memory related problems by effectively eliminating memory leaks and dang

I am reading about the Garbage Collector pattern. It was mentioned that this architectural pattern removes the vast majority of memory related problems by effectively eliminating memory leaks and dangling pointers.

I understand that using a Garbage Collector can remove memory leaks, but how can the Garbage Collector address the issue of dangling pointers? P开发者_JAVA技巧lease give me an example of how problems with dangling pointers can be solved using a Garbage Collector, assuming I am implementing it using a mark and sweep algorithm.

Thanks!


The problem of dangling pointers is handled indirectly: in a GC environment, an object is only deleted when there are no pointers that refer to the object, and as such it will not be deleted in any case where it would leave a dangling pointer. That is, there will be no dangling pointers at all, and the problem cannot occur.


A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed. The following code snippet shows this:

class Sample
{
public:
        int *ptr;
        Sample(int i)
        {
            ptr = new int(i);
        }

        ~Sample()
        {
            delete ptr;
        }
        void PrintVal()
        {
            cout << "The value is " << *ptr;
        }
};

void SomeFunc(Sample x)
{
    cout << "Say i am in someFunc " << endl;
}

int main()
{
    Sample s1 = 10;
    SomeFunc(s1);
    s1.PrintVal();
}

In the above example when PrintVal() function is called it is called by the pointer that has been freed by the destructor in SomeFunc.

0

精彩评论

暂无评论...
验证码 换一张
取 消