简体   繁体   中英

If I use a pointer in a function to populate a list, do I have to delete that pointer at the end of the function in c++?

If I use a pointer in a function to populate a list, do I have to delete that pointer at the end of the function, or the list's destructor will do the work in c++?

For example:

void populateList() {
  Human* human;
  List<Human> myList;

  for (int i = 0; i < 5; ++i) {
    human = new Human();
    myList.push_back(*human);
  }
}

Should I delete the pointer at the end of the function, or it is not needed, because it is not a memory leak?

In this line:

myList.push_back(*human);

you are making a copy of the dynamically allocated object pointed at by the human pointer, so the myList destructor will only clean up that copy. You do need to manually free the dynamically allocated memory pointed at by human , to avoid leaking that memory.

However, in this case there seems to be no reason to dynamically allocate memory with new at all. You could just create a local Human and add that to myList . Then there are no issues with memory leaks since there is no dynamically allocation, and all the objects will be correctly cleaned up when they go out of scope.

There is no need to use a pointer here as you could simply, do this:

void populateList() {
  List<Human> myList;

  for (int i = 0; i < 5; ++i) {
    Human human; //if the constructor of human creates the same thing every time, you could also put this line before the for loop
    myList.push_back(human);
  }
}

Declaring a variable in c++ also constructs it.

What you are doing is creating a pointer, than creating a new instance of Human and making the pointer point to that instance. Than basically copying it to the list, because you are only giving the list a copy. It couldn't delete your pointer even if you wanted to, so you should delete your human instance. If you do insist on using pointers you should do this:

void populateList() {
  Human* human;
  List<Human> myList;

  for (int i = 0; i < 5; ++i) {
    human = new Human();
    myList.push_back(*human);
    delete human;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM