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

后端 未结 9 1017
走了就别回头了
走了就别回头了 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 09:03

    Given two "objects":

    obj a;
    obj b;
    

    They won't occupy the same location in memory. In other words, &a != &b

    Assigning the value of one to the other won't change their location, but it will change their contents:

    obj a;
    obj b = a;
    //a == b, but &a != &b
    

    Intuitively, pointer "objects" work the same way:

    obj *a;
    obj *b = a;
    //a == b, but &a != &b
    

    Now, let's look at your example:

    A *object1 = new A();
    

    This is assigning the value of new A() to object1. The value is a pointer, meaning object1 == new A(), but &object1 != &(new A()). (Note that this example is not valid code, it is only for explanation)

    Because the value of the pointer is preserved, we can free the memory it points to: delete object1; Due to our rule, this behaves the same as delete (new A()); which has no leak.


    For you second example, you are copying the pointed-to object. The value is the contents of that object, not the actual pointer. As in every other case, &object2 != &*(new A()).

    B object2 = *(new B());
    

    We have lost the pointer to the allocated memory, and thus we cannot free it. delete &object2; may seem like it would work, but because &object2 != &*(new A()), it is not equivalent to delete (new A()) and so invalid.

提交回复
热议问题