简体   繁体   中英

C++ deleting pointers

I have a program that contains a doctor class, and each Doctor object has a linked list of "Patients". These patients are created using the following line of code

Patient * patient = new Patient(string firstname, string ailment);

And this patient is then added to a Doctor's linked list. There is a pointer in the Doctor class that is used to point to and iterate through the list and get each patient. When I want to delete these patients, I have to start at the beginning of my list and iterate through each one. My question is, can I delete eacg patient by simply calling their destructors as I iterate through them?

Patient::~Patient(){

}

or do I need to actually call delete on the pointer as it points each employee?

You call delete to delete things. delete will, in turn, result in the object's destructor being called.

Calling the destructor of a class directly is supported by C++, and is in fact useful in some rare scenarios, but it does not actually deallocate the memory. This is not what you want to do here.

First, new returns a pointer, so I guess you mean Patient* patient = ... .

That aside, yes, you'll need to call delete on everything you allocate with new and the destructor will be called.

OR (drumroll) use a std::unique_ptr instead. And I hope when you say you have a list of patients, you mean you have a std::list of patients.

调用delete实际上会调用该对象的析构函数。

Since you are dynamically allocating the memory for each Patient object (should be Patient* patient tho...) you need to manually deallocate each one as well...

Check out this wiki page for more info.

As far as I know you have to call delete on each pointer individually. Deleting a pointer to Patient from within the Patient destructor seems to violate the purpose of using classes (ie they are self contained and don't have access to the outside world).

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