Deleting a pointer in C++

后端 未结 6 1364
旧巷少年郎
旧巷少年郎 2020-11-28 01:11

Context: I\'m trying to wrap my head around pointers, we just saw them a couple of weeks ago in school and while practicing today I ran into a silly? issue, it can be super

6条回答
  •  野性不改
    2020-11-28 02:06

    1 & 2

    myVar = 8; //not dynamically allocated. Can't call delete on it.
    myPointer = new int; //dynamically allocated, can call delete on it.
    

    The first variable was allocated on the stack. You can call delete only on memory you allocated dynamically (on the heap) using the new operator.

    3.

      myPointer = NULL;
      delete myPointer;
    

    The above did nothing at all. You didn't free anything, as the pointer pointed at NULL.


    The following shouldn't be done:

    myPointer = new int;
    myPointer = NULL; //leaked memory, no pointer to above int
    delete myPointer; //no point at all
    

    You pointed it at NULL, leaving behind leaked memory (the new int you allocated). You should free the memory you were pointing at. There is no way to access that allocated new int anymore, hence memory leak.


    The correct way:

    myPointer = new int;
    delete myPointer; //freed memory
    myPointer = NULL; //pointed dangling ptr to NULL
    

    The better way:

    If you're using C++, do not use raw pointers. Use smart pointers instead which can handle these things for you with little overhead. C++11 comes with several.

提交回复
热议问题