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

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

    Well, you create a memory leak if you don't at some point free the memory you've allocated using the new operator by passing a pointer to that memory to the delete operator.

    In your two cases above:

    A *object1 = new A();
    

    Here you aren't using delete to free the memory, so if and when your object1 pointer goes out of scope, you'll have a memory leak, because you'll have lost the pointer and so can't use the delete operator on it.

    And here

    B object2 = *(new B());
    

    you are discarding the pointer returned by new B(), and so can never pass that pointer to delete for the memory to be freed. Hence another memory leak.

提交回复
热议问题