| 1 | #include <boost/ptr_container/ptr_list.hpp>
|
|---|
| 2 | #include <iostream>
|
|---|
| 3 |
|
|---|
| 4 | using namespace std;
|
|---|
| 5 |
|
|---|
| 6 | class BASE
|
|---|
| 7 | {
|
|---|
| 8 | public:
|
|---|
| 9 | virtual int print() const = 0;
|
|---|
| 10 | };
|
|---|
| 11 |
|
|---|
| 12 | class CHILD : public BASE
|
|---|
| 13 | {
|
|---|
| 14 | public:
|
|---|
| 15 | CHILD(int a) :
|
|---|
| 16 | i(a)
|
|---|
| 17 | {
|
|---|
| 18 | }
|
|---|
| 19 | int i;
|
|---|
| 20 |
|
|---|
| 21 | virtual int print() const
|
|---|
| 22 | {
|
|---|
| 23 | return i;
|
|---|
| 24 | }
|
|---|
| 25 | };
|
|---|
| 26 |
|
|---|
| 27 | int main()
|
|---|
| 28 | {
|
|---|
| 29 | // good
|
|---|
| 30 | // boost::ptr_list<BASE> intList;
|
|---|
| 31 | // boost::ptr_list<BASE>::iterator iterIntList;
|
|---|
| 32 | // bad
|
|---|
| 33 | boost::ptr_list<const BASE> intList;
|
|---|
| 34 | boost::ptr_list<const BASE>::iterator iterIntList;
|
|---|
| 35 |
|
|---|
| 36 |
|
|---|
| 37 | BASE *a = new CHILD(1);
|
|---|
| 38 | BASE *b = new CHILD(2);
|
|---|
| 39 | BASE *c = new CHILD(3);
|
|---|
| 40 |
|
|---|
| 41 |
|
|---|
| 42 | intList.push_back(a);
|
|---|
| 43 | intList.push_back(b);
|
|---|
| 44 | intList.push_back(c);
|
|---|
| 45 |
|
|---|
| 46 | for (iterIntList = intList.begin(); iterIntList != intList.end(); iterIntList++)
|
|---|
| 47 | {
|
|---|
| 48 | cout << iterIntList->print() << endl;
|
|---|
| 49 | }
|
|---|
| 50 |
|
|---|
| 51 | intList.clear(); // All pointers held in list are deleted.
|
|---|
| 52 |
|
|---|
| 53 | }
|
|---|