Why does the use of 'new' cause memory leaks?

后端 未结 9 1132
走了就别回头了
走了就别回头了 2020-11-22 08:25

I learned C# first, and now I\'m starting with C++. As I understand, operator new in C++ is not similar to the one in C#.

Can you explain the reason of

9条回答
  •  迷失自我
    2020-11-22 08:49

    A step by step explanation:

    // creates a new object on the heap:
    new B()
    // dereferences the object
    *(new B())
    // calls the copy constructor of B on the object
    B object2 = *(new B());
    

    So by the end of this, you have an object on the heap with no pointer to it, so it's impossible to delete.

    The other sample:

    A *object1 = new A();
    

    is a memory leak only if you forget to delete the allocated memory:

    delete object1;
    

    In C++ there are objects with automatic storage, those created on the stack, which are automatically disposed of, and objects with dynamic storage, on the heap, which you allocate with new and are required to free yourself with delete. (this is all roughly put)

    Think that you should have a delete for every object allocated with new.

    EDIT

    Come to think of it, object2 doesn't have to be a memory leak.

    The following code is just to make a point, it's a bad idea, don't ever like code like this:

    class B
    {
    public:
        B() {};   //default constructor
        B(const B& other) //copy constructor, this will be called
                          //on the line B object2 = *(new B())
        {
            delete &other;
        }
    }
    

    In this case, since other is passed by reference, it will be the exact object pointed to by new B(). Therefore, getting its address by &other and deleting the pointer would free the memory.

    But I can't stress this enough, don't do this. It's just here to make a point.

提交回复
热议问题