tutorial.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. ++++++++++++++++++++++++++++++++++
  2. |Boost| Pointer Container Library
  3. ++++++++++++++++++++++++++++++++++
  4. .. |Boost| image:: boost.png
  5. ========
  6. Tutorial
  7. ========
  8. The tutorial shows you the most simple usage of the
  9. library. It is assumed that the reader is familiar
  10. with the use of standard containers. Although
  11. the tutorial is devided into sections, it is recommended
  12. that you read it all from top to bottom.
  13. * `Basic usage`_
  14. * `Indirected interface`_
  15. * `Sequence containers`_
  16. * `Associative containers`_
  17. * `Null values`_
  18. * `Cloneability`_
  19. * `New functions`_
  20. * `Compatible smart pointer overloads`_
  21. * `Algorithms`_
  22. Basic usage
  23. -----------
  24. The most important aspect of a pointer container is that it manages
  25. memory for you. This means that you in most cases do not need to worry
  26. about deleting memory.
  27. Let us assume that we have an OO-hierarchy of animals
  28. .. parsed-literal::
  29. class animal : `boost::noncopyable <http://www.boost.org/libs/utility/utility.htm#Class_noncopyable>`_
  30. {
  31. public:
  32. virtual ~animal() {}
  33. virtual void eat() = 0;
  34. virtual int age() const = 0;
  35. // ...
  36. };
  37. class mammal : public animal
  38. {
  39. // ...
  40. };
  41. class bird : public animal
  42. {
  43. // ...
  44. };
  45. Then the managing of the animals is straight-forward. Imagine a
  46. Zoo::
  47. class zoo
  48. {
  49. boost::ptr_vector<animal> the_animals;
  50. public:
  51. void add_animal( animal* a )
  52. {
  53. the_animals.push_back( a );
  54. }
  55. };
  56. Notice how we just pass the class name to the container; there
  57. is no ``*`` to indicate it is a pointer.
  58. With this declaration we can now say::
  59. zoo the_zoo;
  60. the_zoo.add_animal( new mammal("joe") );
  61. the_zoo.add_animal( new bird("dodo") );
  62. Thus we heap-allocate all elements of the container
  63. and never rely on copy-semantics.
  64. Indirected interface
  65. --------------------
  66. A particular feature of the pointer containers is that
  67. the query interface is indirected. For example, ::
  68. boost::ptr_vector<animal> vec;
  69. vec.push_back( new animal ); // you add it as pointer ...
  70. vec[0].eat(); // but get a reference back
  71. This indirection also happens to iterators, so ::
  72. typedef std::vector<animal*> std_vec;
  73. std_vec vec;
  74. ...
  75. std_vec::iterator i = vec.begin();
  76. (*i)->eat(); // '*' needed
  77. now becomes ::
  78. typedef boost::ptr_vector<animal> ptr_vec;
  79. ptr_vec vec;
  80. ptr_vec::iterator i = vec.begin();
  81. i->eat(); // no indirection needed
  82. Sequence containers
  83. -------------------
  84. The sequence containers are used when you do not need to
  85. keep an ordering on your elements. You can basically
  86. expect all operations of the normal standard containers
  87. to be available. So, for example, with a ``ptr_deque``
  88. and ``ptr_list`` object you can say::
  89. boost::ptr_deque<animal> deq;
  90. deq.push_front( new animal );
  91. deq.pop_front();
  92. because ``std::deque`` and ``std::list`` have ``push_front()``
  93. and ``pop_front()`` members.
  94. If the standard sequence supports
  95. random access, so does the pointer container; for example::
  96. for( boost::ptr_deque<animal>::size_type i = 0u;
  97. i != deq.size(); ++i )
  98. deq[i].eat();
  99. The ``ptr_vector`` also allows you to specify the size of
  100. the buffer to allocate; for example ::
  101. boost::ptr_vector<animal> animals( 10u );
  102. will reserve room for 10 animals.
  103. Associative containers
  104. ----------------------
  105. To keep an ordering on our animals, we could use a ``ptr_set``::
  106. boost::ptr_set<animal> set;
  107. set.insert( new monkey("bobo") );
  108. set.insert( new whale("anna") );
  109. ...
  110. This requires that ``operator<()`` is defined for animals. One
  111. way to do this could be ::
  112. inline bool operator<( const animal& l, const animal& r )
  113. {
  114. return l.name() < r.name();
  115. }
  116. if we wanted to keep the animals sorted by name.
  117. Maybe you want to keep all the animals in zoo ordered wrt.
  118. their name, but it so happens that many animals have the
  119. same name. We can then use a ``ptr_multimap``::
  120. typedef boost::ptr_multimap<std::string,animal> zoo_type;
  121. zoo_type zoo;
  122. std::string bobo = "bobo",
  123. anna = "anna";
  124. zoo.insert( bobo, new monkey(bobo) );
  125. zoo.insert( bobo, new elephant(bobo) );
  126. zoo.insert( anna, new whale(anna) );
  127. zoo.insert( anna, new emu(anna) );
  128. Note that must create the key as an lvalue
  129. (due to exception-safety issues); the following would not
  130. have compiled ::
  131. zoo.insert( "bobo", // this is bad, but you get compile error
  132. new monkey("bobo") );
  133. If a multimap is not needed, we can use ``operator[]()``
  134. to avoid the clumsiness::
  135. boost::ptr_map<std::string,animal> animals;
  136. animals["bobo"].set_name("bobo");
  137. This requires a default constructor for animals and
  138. a function to do the initialization, in this case ``set_name()``.
  139. A better alternative is to use `Boost.Assign <../../assign/index.html>`_
  140. to help you out. In particular, consider
  141. - `ptr_push_back(), ptr_push_front(), ptr_insert() and ptr_map_insert() <../../assign/doc/index.html#ptr_push_back>`_
  142. - `ptr_list_of() <../../assign/doc/index.html#ptr_list_of>`_
  143. For example, the above insertion may now be written ::
  144. boost::ptr_multimap<std::string,animal> animals;
  145. using namespace boost::assign;
  146. ptr_map_insert<monkey>( animals )( "bobo", "bobo" );
  147. ptr_map_insert<elephant>( animals )( "bobo", "bobo" );
  148. ptr_map_insert<whale>( animals )( "anna", "anna" );
  149. ptr_map_insert<emu>( animals )( "anna", "anna" );
  150. Null values
  151. -----------
  152. By default, if you try to insert null into a container, an exception
  153. is thrown. If you want to allow nulls, then you must
  154. say so explicitly when declaring the container variable ::
  155. boost::ptr_vector< boost::nullable<animal> > animals_type;
  156. animals_type animals;
  157. ...
  158. animals.insert( animals.end(), new dodo("fido") );
  159. animals.insert( animals.begin(), 0 ) // ok
  160. Once you have inserted a null into the container, you must
  161. always check if the value is null before accessing the object ::
  162. for( animals_type::iterator i = animals.begin();
  163. i != animals.end(); ++i )
  164. {
  165. if( !boost::is_null(i) ) // always check for validity
  166. i->eat();
  167. }
  168. If the container support random access, you may also check this as ::
  169. for( animals_type::size_type i = 0u;
  170. i != animals.size(); ++i )
  171. {
  172. if( !animals.is_null(i) )
  173. animals[i].eat();
  174. }
  175. Note that it is meaningless to insert
  176. null into ``ptr_set`` and ``ptr_multiset``.
  177. Cloneability
  178. ------------
  179. In OO programming it is typical to prohibit copying of objects; the
  180. objects may sometimes be allowed to be Cloneable; for example,::
  181. animal* animal::clone() const
  182. {
  183. return do_clone(); // implemented by private virtual function
  184. }
  185. If the OO hierarchy thus allows cloning, we need to tell the
  186. pointer containers how cloning is to be done. This is simply
  187. done by defining a free-standing function, ``new_clone()``,
  188. in the same namespace as
  189. the object hierarchy::
  190. inline animal* new_clone( const animal& a )
  191. {
  192. return a.clone();
  193. }
  194. That is all, now a lot of functions in a pointer container
  195. can exploit the cloneability of the animal objects. For example ::
  196. typedef boost::ptr_list<animal> zoo_type;
  197. zoo_type zoo, another_zoo;
  198. ...
  199. another_zoo.assign( zoo.begin(), zoo.end() );
  200. will fill another zoo with clones of the first zoo. Similarly,
  201. ``insert()`` can now insert clones into your pointer container ::
  202. another_zoo.insert( another_zoo.begin(), zoo.begin(), zoo.end() );
  203. The whole container can now also be cloned ::
  204. zoo_type yet_another_zoo = zoo.clone();
  205. Copying or assigning the container has the same effect as cloning (though it is slightly cheaper)::
  206. zoo_type yet_another_zoo = zoo;
  207. Copying also support derived-to-base class conversions::
  208. boost::ptr_vector<monkey> monkeys = boost::assign::ptr_list_of<monkey>( "bobo" )( "bebe")( "uhuh" );
  209. boost::ptr_vector<animal> animals = monkeys;
  210. This also works for maps::
  211. boost::ptr_map<std::string,monkey> monkeys = ...;
  212. boost::ptr_map<std::string,animal> animals = monkeys;
  213. New functions
  214. -------------
  215. Given that we know we are working with pointers, a few new functions
  216. make sense. For example, say you want to remove an
  217. animal from the zoo ::
  218. zoo_type::auto_type the_animal = zoo.release( zoo.begin() );
  219. the_animal->eat();
  220. animal* the_animal_ptr = the_animal.release(); // now this is not deleted
  221. zoo.release(2); // for random access containers
  222. You can think of ``auto_type`` as a non-copyable form of
  223. ``std::auto_ptr``. Notice that when you release an object, the
  224. pointer is removed from the container and the containers size
  225. shrinks. For containers that store nulls, we can exploit that
  226. ``auto_type`` is convertible to ``bool``::
  227. if( ptr_vector< nullable<T> >::auto_type r = vec.pop_back() )
  228. {
  229. ...
  230. }
  231. You can also release the entire container if you
  232. want to return it from a function ::
  233. compatible-smart-ptr< boost::ptr_deque<animal> > get_zoo()
  234. {
  235. boost::ptr_deque<animal> result;
  236. ...
  237. return result.release(); // give up ownership
  238. }
  239. ...
  240. boost::ptr_deque<animal> animals = get_zoo();
  241. Let us assume we want to move an animal object from
  242. one zoo to another. In other words, we want to move the
  243. animal and the responsibility of it to another zoo ::
  244. another_zoo.transfer( another_zoo.end(), // insert before end
  245. zoo.begin(), // insert this animal ...
  246. zoo ); // from this container
  247. This kind of "move-semantics" is different from
  248. normal value-based containers. You can think of ``transfer()``
  249. as the same as ``splice()`` on ``std::list``.
  250. If you want to replace an element, you can easily do so ::
  251. zoo_type::auto_type old_animal = zoo.replace( zoo.begin(), new monkey("bibi") );
  252. zoo.replace( 2, old_animal.release() ); // for random access containers
  253. A map is slightly different to iterate over than standard maps.
  254. Now we say ::
  255. typedef boost::ptr_map<std::string, boost::nullable<animal> > animal_map;
  256. animal_map map;
  257. ...
  258. for( animal_map::const_iterator i = map.begin(), e = map.end(); i != e; ++i )
  259. {
  260. std::cout << "\n key: " << i->first;
  261. std::cout << "\n age: ";
  262. if( boost::is_null(i) )
  263. std::cout << "unknown";
  264. else
  265. std::cout << i->second->age();
  266. }
  267. Except for the check for null, this looks like it would with a normal map. But if ``age()`` had
  268. not been a ``const`` member function,
  269. it would not have compiled.
  270. Maps can also be indexed with bounds-checking ::
  271. try
  272. {
  273. animal& bobo = map.at("bobo");
  274. }
  275. catch( boost::bad_ptr_container_operation& e )
  276. {
  277. // "bobo" not found
  278. }
  279. Compatible smart pointer overloads
  280. ----------------------------------
  281. Every time there is a function that takes a ``T*`` parameter, there is
  282. also a function overload (or two) taking a ``compatible-smart-ptr<U>``
  283. parameter. This is of course done to make the library intregrate
  284. seamlessly with ``std::auto_ptr`` or ``std::unique_ptr``. For example,
  285. consider a statement like ::
  286. std::ptr_vector<Base> vec;
  287. vec.push_back( new Base );
  288. If the compiler supports ``std::auto_ptr``, this is complemented
  289. by ::
  290. std::auto_ptr<Derived> p( new Derived );
  291. vec.push_back( p );
  292. Similarly if ``std::unique_ptr`` is available, we can write ::
  293. std::unique_ptr<Derived> p( new Derived );
  294. vec.push_back( std::move( p ) );
  295. Notice that the template argument for ``compatible-smart-ptr`` does not need to
  296. follow the template argument for ``ptr_vector`` as long as ``Derived*``
  297. can be implicitly converted to ``Base*``.
  298. Algorithms
  299. ----------
  300. Unfortunately it is not possible to use pointer containers with
  301. mutating algorithms from the standard library. However,
  302. the most useful ones
  303. are instead provided as member functions::
  304. boost::ptr_vector<animal> zoo;
  305. ...
  306. zoo.sort(); // assume 'bool operator<( const animal&, const animal& )'
  307. zoo.sort( std::less<animal>() ); // the same, notice no '*' is present
  308. zoo.sort( zoo.begin(), zoo.begin() + 5 ); // sort selected range
  309. Notice that predicates are automatically wrapped in an `indirect_fun`_ object.
  310. .. _`indirect_fun`: indirect_fun.html
  311. You can remove equal and adjacent elements using ``unique()``::
  312. zoo.unique(); // assume 'bool operator==( const animal&, const animal& )'
  313. zoo.unique( zoo.begin(), zoo.begin() + 5, my_comparison_predicate() );
  314. If you just want to remove certain elements, use ``erase_if``::
  315. zoo.erase_if( my_predicate() );
  316. Finally you may want to merge two sorted containers::
  317. boost::ptr_vector<animal> another_zoo = ...;
  318. another_zoo.sort(); // sorted wrt. to same order as 'zoo'
  319. zoo.merge( another_zoo );
  320. BOOST_ASSERT( another_zoo.empty() );
  321. That is all; now you have learned all the basics!
  322. .. raw:: html
  323. <hr>
  324. **See also**
  325. - `Usage guidelines <guidelines.html>`_
  326. - `Cast utilities <../../conversion/cast.htm#Polymorphic_castl>`_
  327. **Navigate**
  328. - `home <ptr_container.html>`_
  329. - `examples <examples.html>`_
  330. .. raw:: html
  331. <hr>
  332. :Copyright: Thorsten Ottosen 2004-2006. Use, modification and distribution is subject to the Boost Software License, Version 1.0 (see LICENSE_1_0.txt__).
  333. __ http://www.boost.org/LICENSE_1_0.txt