#include <boost/ptr_container/ptr_list.hpp>
#include <iostream>
using namespace std;
class ABC
{
public:
int i;
float j;
};
main()
{
boost::ptr_list<ABC> intList;
boost::ptr_list<ABC>::iterator iterIntList;
ABC *a= new ABC;
ABC *b= new ABC;
ABC *c= new ABC;
a->i = 1;
b->i = 2;
c->i = 3;
intList.push_back(a);
intList.push_back(b);
intList.push_back(c);
for (iterIntList = intList.begin();
iterIntList != intList.end();
iterIntList++)
{
cout << iterIntList->i << endl;
}
intList.clear(); // All pointers held in list are deleted.
}
Compile: g++ testBoostPtrList.cpp
Run: ./a.out
1See http://www.boost.org/libs/ptr_container/doc/ptr_list.html
2
3
Red Hat RPM packages: boost, boost-devel
Newer Linux releases like Red Hat Enterprise 5/CentOS 5 include boost "ptr_list".
RHEL4 included boost libraries but did not include "ptr_list".
Ubuntu installation: apt-get install libboost-dev libboost-doc
// g++ -g testStlPtrList.cpp
#include <iostream>
#include <list>
using namespace std;
class ABC
{
public:
int i;
float j;
};
main()
{
list<ABC*> intList;
list<ABC*>::iterator iterIntList;
ABC *a= new ABC;
ABC *b= new ABC;
ABC *c= new ABC;
a->i = 1;
b->i = 2;
c->i = 3;
intList.push_back(a);
intList.push_back(b);
intList.push_back(c);
for (iterIntList = intList.begin();
iterIntList != intList.end();
iterIntList++)
{
cout << (*iterIntList)->i << endl;
}
// Free pointers
for (iterIntList = intList.begin();
iterIntList != intList.end();
iterIntList++)
{
delete *iterIntList;
}
intList.clear(); // List is deleted.
}
For more information on STL list, see the YoLinux.com STL vector and STL list tutorial
You can test the above programs and investigate their respective memory clean-up in GDB.
See the YoLinux.com GDB tutorial.
Using GDB:
- Compile with debugging enabled: g++ -g -o testStlPtrList testStlPtrList.cpp
- Start GDB: gdb testStlPtrList
- Show listing with line numbers: list
- Set break point: break 30
- Run program till break point: run
- Find memory location of variable in GDB: print &(c->i)
(gdb) p &(c->i)
$4 = (int *) 0x503050
- Dereference memory location: p (*0x503050)
(gdb) p (*0x503050)
$5 = 3
- Dereference memory location after memory is freed: p (*0x503050)
(gdb) p (*0x503050)
Using RHEL5. Note older systems may give you a nonsense value.
$7 = 0


Books:






