Notice: Any messages purporting to come from this site telling you that your password has expired, or that you need to verify your details, confirm your email, resolve issues, making threats, or asking for money, are
spam. We do not email users with any such messages. If you have lost your password you can obtain a new one by using the
password reset link.
Due to spam on this forum, all posts now need moderator approval.
Entire forum
➜ Programming
➜ STL
➜ Deleting Pointers
It is now over 60 days since the last post. This thread is closed.
Refresh page
| Posted by
| Nick Gammon
Australia (23,173 posts) Bio
Forum Administrator |
| Date
| Wed 02 Jul 2003 06:34 AM (UTC) Amended on Wed 24 Sep 2003 02:29 AM (UTC) by Nick Gammon
|
| Message
| If you have a container of pointers you cannot just remove the elements from the container, you also need to delete the data the pointers are pointing to (presumably). Here is a nifty way of doing that ...
struct DeleteObject
{
template <typename T>
void operator() (const T* ptr) const { delete ptr; };
};
You can these use this in a for_each statement. Here is an example ...
#include <string>
#include <list>
#include <algorithm>
using namespace std;
struct DeleteObject
{
template <typename T>
void operator() (const T* ptr) const { delete ptr; };
};
class Person
{
public:
// constructor
Person (const string sName,
const string sEmail,
const int iAge) :
m_sName (sName), m_sEmail (sEmail), m_iAge (iAge) {};
string m_sName;
string m_sEmail;
int m_iAge;
};
typedef list<Person*> PersonList;
int main (void)
{
PersonList people;
// add items to list
people.push_back (new Person ("Nick", "nick@some-email-address.com", 15));
people.push_back (new Person ("Fred", "fred@nurk.com.au", 100));
// delete all objects in list
for_each (people.begin (), people.end (), DeleteObject ());
// now delete them from the list
people.clear ();
return 0;
} // end of main
The DeleteObject function is a template so it automatically deletes the right sort of object.
|
- Nick Gammon
www.gammon.com.au, www.mushclient.com | | Top |
|
The dates and times for posts above are shown in Universal Co-ordinated Time (UTC).
To show them in your local time you can join the forum, and then set the 'time correction' field in your profile to the number of hours difference between your location and UTC time.
6,451 views.
It is now over 60 days since the last post. This thread is closed.
Refresh page
top