count_bdy.htm 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Language" content="en-us">
  5. <meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
  6. <meta name="GENERATOR" content="Microsoft FrontPage 6.0">
  7. <meta name="Author" content="Kevlin Henney">
  8. <meta name="KeyWords" content=
  9. "C++, Reference Counting, Advanced Techniques, Smart Pointers, Patterns">
  10. <title>Counted Body Techniques</title>
  11. </head>
  12. <body bgcolor="#FFFFFF" text="#000000">
  13. <h1 align="center"><i><font size="+4">Counted Body Techniques</font></i></h1>
  14. <center>
  15. <p><b><font size="+1"><a href="../people/kevlin_henney.htm">Kevlin Henney</a><br></font>
  16. (<a href=
  17. "mailto:kevlin@acm.org">kevlin@acm.org</a>, <a href=
  18. "mailto:khenney@qatraining.com">khenney@qatraining.com</a>)</b></p>
  19. </center>
  20. <div style="margin-left: 2em">
  21. <p>Reference counting techniques? Nothing new, you might think. Every good
  22. C++ text that takes you to an intermediate or advanced level will
  23. introduce the concept. It has been explored with such thoroughness in the
  24. past that you might be forgiven for thinking that everything that can be
  25. said has been said. Well, let's start from first principles and see if we
  26. can unearth something new....</p>
  27. </div>
  28. <hr width="100%">
  29. <h2>And then there were none...</h2>
  30. <div style="margin-left: 2em">
  31. <p>The principle behind reference counting is to keep a running usage
  32. count of an object so that when it falls to zero we know the object is
  33. unused. This is normally used to simplify the memory management for
  34. dynamically allocated objects: keep a count of the number of references
  35. held to that object and, on zero, delete the object.</p>
  36. <p>How to keep a track of the number of users of an object? Well, normal
  37. pointers are quite dumb, and so an extra level of indirection is required
  38. to manage the count. This is essentially the P<font size="-1">ROXY</font>
  39. pattern described in <i>Design Patterns</i> [Gamma, Helm, Johnson &amp;
  40. Vlissides, Addison-Wesley, <font size="-1">ISBN</font> 0-201-63361-2]. The
  41. intent is given as</p>
  42. <div style="margin-left: 2em">
  43. <p><i>Provide a surrogate or placeholder for another object to control
  44. access to it.</i></p>
  45. </div>
  46. <p>Coplien [<i>Advanced C++ Programming Styles and Idioms</i>,
  47. Addison-Wesley, <font size="-1">ISBN</font> 0-201-56365-7] defines a set
  48. of idioms related to this essential separation of a handle and a body
  49. part. The <i>Taligent Guide to Designing Programs</i> [Addison-Wesley,
  50. <font size="-1">ISBN</font> 0-201-40888-0] identifies a number of specific
  51. categories for proxies (aka surrogates). Broadly speaking they fall into
  52. two general categories:</p>
  53. <ul>
  54. <li><i>Hidden</i>: The handle is the object of interest, hiding the body
  55. itself. The functionality of the handle is obtained by delegation to the
  56. body, and the user of the handle is unaware of the body. Reference
  57. counted strings offer a transparent optimisation. The body is shared
  58. between copies of a string until such a time as a change is needed, at
  59. which point a copy is made. Such a C<font size=
  60. "-1">OPY</font> <font size="-1">ON</font> W<font size="-1">RITE</font>
  61. pattern (a specialisation of L<font size="-1">AZY</font> E<font size=
  62. "-1">VALUATION</font>) requires the use of a hidden reference counted
  63. body.</li>
  64. <li><i>Explicit</i>: Here the body is of interest and the handle merely
  65. provides intelligence for its access and housekeeping. In C++ this is
  66. often implemented as the S<font size="-1">MART</font> P<font size=
  67. "-1">OINTER</font> idiom. One such application is that of reference
  68. counted smart pointers that collaborate to keep a count of an object,
  69. deleting it when the count falls to zero.</li>
  70. </ul>
  71. </div>
  72. <hr width="100%">
  73. <h2>Attached vs detached</h2>
  74. <div style="margin-left: 2em">
  75. <p>For reference counted smart pointers there are two places the count can
  76. exist, resulting in two different patterns, both outlined in
  77. <i>Software Patterns</i> [Coplien, SIGS, <font size="-1">ISBN</font>
  78. 0-884842-50-X]:</p>
  79. <ul>
  80. <li>C<font size="-1">OUNTED</font> B<font size="-1">ODY</font> or A<font size="-1">TTACHED</font>
  81. C<font size="-1">OUNTED</font>
  82. H<font size="-1">ANDLE</font>/B<font size="-1">ODY</font> places the
  83. count within the object being counted. The benefits are that
  84. countability is a part of the object being counted, and that reference
  85. counting does not require an additional object. The drawbacks are
  86. clearly that this is intrusive, and that the space for the reference
  87. count is wasted when the object is not heap based. Therefore the
  88. reference counting ties you to a particular implementation and style of
  89. use.</li>
  90. <li>D<font size="-1">ETACHED</font> C<font size="-1">OUNTED</font>
  91. H<font size="-1">ANDLE</font>/B<font size="-1">ODY</font> places the
  92. count outside the object being counted, such that they are handled
  93. together. The clear benefit of this is that this technique is completely
  94. unintrusive, with all of the intelligence and support apparatus in the
  95. smart pointer, and therefore can be used on classes created
  96. independently of the reference counted pointer. The main disadvantage is
  97. that frequent use of this can lead to a proliferation of small objects,
  98. i.e. the counter, being created on the heap.</li>
  99. </ul>
  100. <p>Even with this simple analysis, it seems that the D<font size=
  101. "-1">ETACHED</font> C<font size="-1">OUNTED</font> H<font size=
  102. "-1">ANDLE</font>/B<font size="-1">ODY</font> approach is ahead. Indeed,
  103. with the increasing use of templates this is often the favourite, and is
  104. the principle behind the common - but not standard - <tt><font size=
  105. "+1">counted_ptr</font></tt>. <i>[The Boost name is <a href=
  106. "../libs/smart_ptr/shared_ptr.htm"><tt><font size=
  107. "+1">shared_ptr</font></tt></a> rather than <tt><font size=
  108. "+1">counted_ptr</font></tt>.]</i></p>
  109. <p>A common implementation of C<font size="-1">OUNTED</font> B<font size=
  110. "-1">ODY</font> is to provide the counting mechanism in a base class that
  111. the counted type is derived from. Either that, or the reference counting
  112. mechanism is provided anew for each class that needs it. Both of these
  113. approaches are unsatisfactory because they are quite closed, coupling a
  114. class into a particular framework. Added to this the non-cohesiveness of
  115. having the count lying dormant in a non-counted object, and you get the
  116. feeling that excepting its use in widespread object models such as COM and
  117. CORBA the C<font size="-1">OUNTED</font> B<font size="-1">ODY</font>
  118. approach is perhaps only of use in specialised situations.</p>
  119. </div>
  120. <hr width="100%">
  121. <h2>A requirements based approach</h2>
  122. <div style="margin-left: 2em">
  123. <p>It is the question of openness that convinced me to revisit the
  124. problems with the C<font size="-1">OUNTED</font> B<font size=
  125. "-1">ODY</font> idiom. Yes, there is a certain degree of intrusion
  126. expected when using this idiom, but is there anyway to minimise this and
  127. decouple the choice of counting mechanism from the smart pointer type
  128. used?</p>
  129. <p>In recent years the most instructive body of code and specification for
  130. constructing open general purpose components has been the Stepanov and
  131. Lee's STL (Standard Template Library), now part of the C++ standard
  132. library. The STL approach makes extensive use of compile time polymorphism
  133. based on well defined operational requirements for types. For instance,
  134. each container, contained and iterator type is defined by the operations
  135. that should be performable on an object of that type, often with
  136. annotations describing additional constraints. Compile time polymorphism,
  137. as its name suggests, resolves functions at compile time based on function
  138. name and argument usage, i.e. overloading. This is less intrusive,
  139. although less easily diagnosed if incorrect, than runtime poymorphism that
  140. is based on types, names and function signatures.</p>
  141. <p>This requirements based approach can be applied to reference counting.
  142. The operations we need for a type to be <i>Countable</i> are loosely:</p>
  143. <ul>
  144. <li>An <tt><font size="+1">acquire</font></tt> operation that registers
  145. interest in a <i>Countable</i> object.</li>
  146. <li>A <tt><font size="+1">release</font></tt> operation unregisters
  147. interest in a <i>Countable</i> object.</li>
  148. <li>An <tt><font size="+1">acquired</font></tt> query that returns
  149. whether or not a <i>Countable</i> object is currently acquired.</li>
  150. <li>A <tt><font size="+1">dispose</font></tt> operation that is
  151. responsible for disposing of an object that is no longer acquired.</li>
  152. </ul>
  153. <p>Note that the count is deduced as a part of the abstract state of this
  154. type, and is not mentioned or defined in any other way. The openness of
  155. this approach derives in part from the use of global functions, meaning
  156. that no particular member functions are implied; a perfect way to wrap up
  157. an existing counted body class without modifying the class itself. The
  158. other aspect to the openness comes from a more precise specification of
  159. the operations.</p>
  160. <p>For a type to be <i>Countable</i> it must satisfy the following
  161. requirements, where <tt><font size="+1">ptr</font></tt> is a non-null
  162. pointer to a single object (i.e. not an array) of the type, and
  163. <i><tt><font size="+1">#function</font></tt></i> indicates number of calls
  164. to <tt><font size="+1"><i>function(</i>ptr<i>)</i></font></tt>:</p>
  165. <center>
  166. <table border="1" cellspacing="2" cellpadding="2" summary="">
  167. <tr>
  168. <td><i>Expression</i></td>
  169. <td><i>Return type</i></td>
  170. <td><i>Semantics and notes</i></td>
  171. </tr>
  172. <tr>
  173. <td><tt><font size="+1">acquire(ptr)</font></tt></td>
  174. <td>no requirement</td>
  175. <td><i>post</i>: <tt><font size="+1">acquired(ptr)</font></tt></td>
  176. </tr>
  177. <tr>
  178. <td><tt><font size="+1">release(ptr)</font></tt></td>
  179. <td>no requirement</td>
  180. <td><i>pre</i>: <tt><font size="+1">acquired(ptr)<br></font></tt>
  181. <i>post</i>: <tt><font size="+1">acquired(ptr) == #acquire -
  182. #release</font></tt></td>
  183. </tr>
  184. <tr>
  185. <td><tt><font size="+1">acquired(ptr)</font></tt></td>
  186. <td>convertible to <tt><font size="+1">bool</font></tt></td>
  187. <td><i>return</i>: <tt><font size="+1">#acquire &gt; #release</font></tt></td>
  188. </tr>
  189. <tr>
  190. <td><tt><font size="+1">dispose(ptr, ptr)</font></tt></td>
  191. <td>no requirement</td>
  192. <td><i>pre</i>: <tt><font size="+1">!acquired(ptr)<br></font></tt>
  193. <i>post</i>: <tt><font size="+1">*ptr</font></tt> no longer usable</td>
  194. </tr>
  195. </table>
  196. </center>
  197. <p>Note that the two arguments to <tt><font size="+1">dispose</font></tt>
  198. are to support selection of the appropriate type safe version of the
  199. function to be called. In the general case the intent is that the first
  200. argument determines the type to be deleted, and would typically be
  201. templated, while the second selects which template to use, e.g. by
  202. conforming to a specific base class.</p>
  203. <p>In addition the following requirements must also be satisfied, where
  204. <tt><font size="+1">null</font></tt> is a null pointer to the
  205. <i>Countable</i> type:</p>
  206. <center>
  207. <table border="1" summary="">
  208. <tr>
  209. <td><i>Expression</i></td>
  210. <td><i>Return type</i></td>
  211. <td><i>Semantics and notes</i></td>
  212. </tr>
  213. <tr>
  214. <td><tt><font size="+1">acquire(null)</font></tt></td>
  215. <td>no requirement</td>
  216. <td><i>action</i>: none</td>
  217. </tr>
  218. <tr>
  219. <td><tt><font size="+1">release(null)</font></tt></td>
  220. <td>no requirement</td>
  221. <td><i>action</i>: none</td>
  222. </tr>
  223. <tr>
  224. <td><tt><font size="+1">acquired(null)</font></tt></td>
  225. <td>convertible to <tt><font size="+1">bool</font></tt></td>
  226. <td><i>return</i>: <tt><font size="+1">false</font></tt></td>
  227. </tr>
  228. <tr>
  229. <td><tt><font size="+1">dispose(null, null)</font></tt></td>
  230. <td>no requirement</td>
  231. <td><i>action</i>: none</td>
  232. </tr>
  233. </table>
  234. </center>
  235. <p>Note that there are no requirements on these functions in terms of
  236. exceptions thrown or not thrown, except that if exceptions are thrown the
  237. functions themselves should be exception safe.</p>
  238. </div>
  239. <hr width="100%">
  240. <h2>Getting smart</h2>
  241. <div style="margin-left: 2em">
  242. <p>Given the <i>Countable</i> requirements for a type, it is possible to
  243. define a generic smart pointer type that uses them for reference counting:</p>
  244. <div style="margin-left: 2em">
  245. <pre>
  246. <tt>template&lt;typename countable_type&gt;
  247. class countable_ptr
  248. {
  249. public: // construction and destruction
  250. explicit countable_ptr(countable_type *);
  251. countable_ptr(const countable_ptr &amp;);
  252. ~countable_ptr();
  253. public: // access
  254. countable_type *operator-&gt;() const;
  255. countable_type &amp;operator*() const;
  256. countable_type *get() const;
  257. public: // modification
  258. countable_ptr &amp;clear();
  259. countable_ptr &amp;assign(countable_type *);
  260. countable_ptr &amp;assign(const countable_ptr &amp;);
  261. countable_ptr &amp;operator=(const countable_ptr &amp;);
  262. private: // representation
  263. countable_type *body;
  264. };
  265. </tt>
  266. </pre>
  267. </div>
  268. <p>The interface to this class has been kept intentionally simple, e.g.
  269. member templates and <tt><font size="+1">throw</font></tt> specs have been
  270. omitted, for exposition. The majority of the functions are quite simple in
  271. implementation, relying very much on the <tt><font size=
  272. "+1">assign</font></tt> member as a keystone function:</p>
  273. <div style="margin-left: 2em">
  274. <pre>
  275. <tt>template&lt;typename countable_type&gt;
  276. countable_ptr&lt;countable_type&gt;::countable_ptr(countable_type *initial)
  277. : body(initial)
  278. {
  279. acquire(body);
  280. }
  281. template&lt;typename countable_type&gt;
  282. countable_ptr&lt;countable_type&gt;::countable_ptr(const countable_ptr &amp;other)
  283. : body(other.body)
  284. {
  285. acquire(body);
  286. }
  287. template&lt;typename countable_type&gt;
  288. countable_ptr&lt;countable_type&gt;::~countable_ptr()
  289. {
  290. clear();
  291. }
  292. template&lt;typename countable_type&gt;
  293. countable_type *countable_ptr&lt;countable_type&gt;::operator-&gt;() const
  294. {
  295. return body;
  296. }
  297. template&lt;typename countable_type&gt;
  298. countable_type &amp;countable_ptr&lt;countable_type&gt;::operator*() const
  299. {
  300. return *body;
  301. }
  302. template&lt;typename countable_type&gt;
  303. countable_type *countable_ptr&lt;countable_type&gt;::get() const
  304. {
  305. return body;
  306. }
  307. template&lt;typename countable_type&gt;
  308. countable_ptr&lt;countable_type&gt; &amp;countable_ptr&lt;countable_type&gt;::clear()
  309. {
  310. return assign(0);
  311. }
  312. template&lt;typename countable_type&gt;
  313. countable_ptr&lt;countable_type&gt; &amp;countable_ptr&lt;countable_type&gt;::assign(countable_type *rhs)
  314. {
  315. // set to rhs (uses Copy Before Release idiom which is self assignment safe)
  316. acquire(rhs);
  317. countable_type *old_body = body;
  318. body = rhs;
  319. // tidy up
  320. release(old_body);
  321. if(!acquired(old_body))
  322. {
  323. dispose(old_body, old_body);
  324. }
  325. return *this;
  326. }
  327. template&lt;typename countable_type&gt;
  328. countable_ptr&lt;countable_type&gt; &amp;countable_ptr&lt;countable_type&gt;::assign(const countable_ptr &amp;rhs)
  329. {
  330. return assign(rhs.body);
  331. }
  332. template&lt;typename countable_type&gt;
  333. countable_ptr&lt;countable_type&gt; &amp;countable_ptr&lt;countable_type&gt;::operator=(const countable_ptr &amp;rhs)
  334. {
  335. return assign(rhs);
  336. }
  337. </tt>
  338. </pre>
  339. </div>
  340. </div>
  341. <hr width="100%">
  342. <h2>Public accountability</h2>
  343. <div style="margin-left: 2em">
  344. <p>Conformance to the requirements means that a type can be used with
  345. <tt><font size="+1">countable_ptr</font></tt>. Here is an implementation
  346. mix-in class (<i>mix-imp</i>) that confers countability on its derived
  347. classes through member functions. This class can be used as a class
  348. adaptor:</p>
  349. <div style="margin-left: 2em">
  350. <pre>
  351. <tt>class countability
  352. {
  353. public: // manipulation
  354. void acquire() const;
  355. void release() const;
  356. size_t acquired() const;
  357. protected: // construction and destruction
  358. countability();
  359. ~countability();
  360. private: // representation
  361. mutable size_t count;
  362. private: // prevention
  363. countability(const countability &amp;);
  364. countability &amp;operator=(const countability &amp;);
  365. };
  366. </tt>
  367. </pre>
  368. </div>
  369. <p>Notice that the manipulation functions are <tt><font size=
  370. "+1">const</font></tt> and that the <tt><font size="+1">count</font></tt>
  371. member itself is <tt><font size="+1">mutable</font></tt>. This is because
  372. countability is not a part of an object's abstract state: memory
  373. management does not depend on the <tt><font size=
  374. "+1">const</font></tt>-ness or otherwise of an object. I won't include the
  375. definitions of the member functions here as you can probably guess them:
  376. increment, decrement and return the current count, respectively for the
  377. manipulation functions. In a multithreaded environment you should ensure
  378. that such read and write operations are atomic.</p>
  379. <p>So how do we make this class <i>Countable</i>? A simple set of
  380. forwarding functions does the job:</p>
  381. <div style="margin-left: 2em">
  382. <pre>
  383. <tt>void acquire(const countability *ptr)
  384. {
  385. if(ptr)
  386. {
  387. ptr-&gt;acquire();
  388. }
  389. }
  390. void release(const countability *ptr)
  391. {
  392. if(ptr)
  393. {
  394. ptr-&gt;release();
  395. }
  396. }
  397. size_t acquired(const countability *ptr)
  398. {
  399. return ptr ? ptr-&gt;acquired() : 0;
  400. }
  401. template&lt;class countability_derived&gt;
  402. void dispose(const countability_derived *ptr, const countability *)
  403. {
  404. delete ptr;
  405. }
  406. </tt>
  407. </pre>
  408. </div>
  409. <p>Any type that now derives from <tt><font size=
  410. "+1">countability</font></tt> may now be used with <tt><font size=
  411. "+1">countable_ptr</font></tt>:</p>
  412. <div style="margin-left: 2em">
  413. <pre>
  414. <tt>class example : public countability
  415. {
  416. ...
  417. };
  418. void simple()
  419. {
  420. countable_ptr&lt;example&gt; ptr(new example);
  421. countable_ptr&lt;example&gt; qtr(ptr);
  422. ptr.clear(); // set ptr to point to null
  423. } // allocated object deleted when qtr destructs
  424. </tt>
  425. </pre>
  426. </div>
  427. </div>
  428. <hr width="100%">
  429. <h2>Runtime mixin</h2>
  430. <div style="margin-left: 2em">
  431. <p>The challenge is to apply C<font size="-1">OUNTED</font> B<font size=
  432. "-1">ODY</font> in a non-intrusive fashion, such that there is no overhead
  433. when an object is not counted. What we would like to do is confer this
  434. capability on a per object rather than on a per class basis. Effectively
  435. we are after <i>Countability</i> on any object, i.e. anything pointed to
  436. by a <tt><font size="+1">void *</font></tt>! It goes without saying that <tt><font size="+1">
  437. void</font></tt> is perhaps the least committed of any type.</p>
  438. <p>The forces to resolve on this are quite interesting, to say the least.
  439. Interesting, but not insurmountable. Given that the class of a runtime
  440. object cannot change dynamically in any well defined manner, and the
  441. layout of the object must be fixed, we have to find a new place and time
  442. to add the counting state. The fact that this must be added only on heap
  443. creation suggests the following solution:</p>
  444. <div style="margin-left: 2em">
  445. <pre>
  446. <tt>struct countable_new;
  447. extern const countable_new countable;
  448. void *operator new(size_t, const countable_new &amp;);
  449. void operator delete(void *, const countable_new &amp;);</tt>
  450. </pre>
  451. </div>
  452. <p>We have overloaded <tt><font size="+1">operator new</font></tt> with a
  453. dummy argument to distinguish it from the regular global <tt><font size=
  454. "+1">operator new</font></tt>. This is comparable to the use of the
  455. <tt><font size="+1">std::nothrow_t</font></tt> type and <tt><font size=
  456. "+1">std::nothrow</font></tt> object in the standard library. The
  457. placement <tt><font size="+1">operator delete</font></tt> is there to
  458. perform any tidy up in the event of failed construction. Note that this is
  459. not yet supported on all that many compilers.</p>
  460. <p>The result of a <tt><font size="+1">new</font></tt> expression using
  461. <tt><font size="+1">countable</font></tt> is an object allocated on the
  462. heap that has a header block that holds the count, i.e. we have extended
  463. the object by prefixing it. We can provide a couple of features in an
  464. anonymous namespace (not shown) in the implementation file for for
  465. supporting the count and its access from a raw pointer:</p>
  466. <div style="margin-left: 2em">
  467. <pre>
  468. <tt>struct count
  469. {
  470. size_t value;
  471. };
  472. count *header(const void *ptr)
  473. {
  474. return const_cast&lt;count *&gt;(static_cast&lt;const count *&gt;(ptr) - 1);
  475. }
  476. </tt>
  477. </pre>
  478. </div>
  479. <p>An important constraint to observe here is the alignment of
  480. <tt><font size="+1">count</font></tt> should be such that it is suitably
  481. aligned for any type. For the definition shown this will be the case on
  482. almost all platforms. However, you may need to add a padding member for
  483. those that don't, e.g. using an anonymous <tt><font size=
  484. "+1">union</font></tt> to coalign <tt><font size="+1">count</font></tt>
  485. and the most aligned type. Unfortunately, there is no portable way of
  486. specifying this such that the minimum alignment is also observed - this is
  487. a common problem when specifying your own allocators that do not directly
  488. use the results of either <tt><font size="+1">new</font></tt> or
  489. <tt><font size="+1">malloc</font></tt>.</p>
  490. <p>Again, note that the count is not considered to be a part of the
  491. logical state of the object, and hence the conversion from
  492. <tt><font size="+1">const</font></tt> to non-<tt><font size=
  493. "+1">const</font></tt> - <tt><font size="+1">count</font></tt> is in
  494. effect a <tt><font size="+1">mutable</font></tt> type.</p>
  495. <p>The allocator functions themselves are fairly straightforward:</p>
  496. <div style="margin-left: 2em">
  497. <pre>
  498. <tt>void *operator new(size_t size, const countable_new &amp;)
  499. {
  500. count *allocated = static_cast&lt;count *&gt;(::operator new(sizeof(count) + size));
  501. *allocated = count(); // initialise the header
  502. return allocated + 1; // adjust result to point to the body
  503. }
  504. void operator delete(void *ptr, const countable_new &amp;)
  505. {
  506. ::operator delete(header(ptr));
  507. }
  508. </tt>
  509. </pre>
  510. </div>
  511. <p>Given a correctly allocated header, we now need the <i>Countable</i>
  512. functions to operate on <tt><font size="+1">const void *</font></tt> to
  513. complete the picture:</p>
  514. <div style="margin-left: 2em">
  515. <pre>
  516. <tt>void acquire(const void *ptr)
  517. {
  518. if(ptr)
  519. {
  520. ++header(ptr)-&gt;value;
  521. }
  522. }
  523. void release(const void *ptr)
  524. {
  525. if(ptr)
  526. {
  527. --header(ptr)-&gt;value;
  528. }
  529. }
  530. size_t acquired(const void *ptr)
  531. {
  532. return ptr ? header(ptr)-&gt;value : 0;
  533. }
  534. template&lt;typename countable_type&gt;
  535. void dispose(const countable_type *ptr, const void *)
  536. {
  537. ptr-&gt;~countable_type();
  538. operator delete(const_cast&lt;countable_type *&gt;(ptr), countable);
  539. }
  540. </tt>
  541. </pre>
  542. </div>
  543. <p>The most complex of these is the <tt><font size=
  544. "+1">dispose</font></tt> function that must ensure that the correct type
  545. is destructed and also that the memory is collected from the correct
  546. offset. It uses the value and type of first argument to perform this
  547. correctly, and the second argument merely acts as a strategy selector,
  548. i.e. the use of <tt><font size="+1">const void *</font></tt>
  549. distinguishes it from the earlier dispose shown for <tt><font size=
  550. "+1">const countability *</font></tt>.</p>
  551. </div>
  552. <hr width="100%">
  553. <h2>Getting smarter</h2>
  554. <div style="margin-left: 2em">
  555. <p>Now that we have a way of adding countability at creation for objects
  556. of any type, what extra is needed to make this work with the
  557. <tt><font size="+1">countable_ptr</font></tt> we defined earlier? Good
  558. news: nothing!</p>
  559. <div style="margin-left: 2em">
  560. <pre>
  561. <tt>class example
  562. {
  563. ...
  564. };
  565. void simple()
  566. {
  567. countable_ptr&lt;example&gt; ptr(new(countable) example);
  568. countable_ptr&lt;example&gt; qtr(ptr);
  569. ptr.clear(); // set ptr to point to null
  570. } // allocated object deleted when qtr destructs
  571. </tt>
  572. </pre>
  573. </div>
  574. <p>The <tt><font size="+1">new(countable)</font></tt> expression defines a
  575. different policy for allocation and deallocation and, in common with other
  576. allocators, any attempt to mix your allocation policies, e.g. call
  577. <tt><font size="+1">delete</font></tt> on an object allocated with
  578. <tt><font size="+1">new(countable)</font></tt>, results in undefined
  579. behaviour. This is similar to what happens when you mix <tt><font size=
  580. "+1">new[]</font></tt> with <tt><font size="+1">delete</font></tt> or
  581. <tt><font size="+1">malloc</font></tt> with <tt><font size=
  582. "+1">delete</font></tt>. The whole point of <i>Countable</i> conformance
  583. is that <i>Countable</i> objects are used with <tt><font size=
  584. "+1">countable_ptr</font></tt>, and this ensures the correct use.</p>
  585. <p>However, accidents will happen, and inevitably you may forget to
  586. allocate using <tt><font size="+1">new(countable)</font></tt> and instead
  587. use <tt><font size="+1">new</font></tt>. This error and others can be
  588. detected in most cases by extending the code shown here to add a check
  589. member to the <tt><font size="+1">count</font></tt>, validating the check
  590. on every access. A benefit of ensuring clear separation between header and
  591. implementation source files means that you can introduce a checking
  592. version of this allocator without having to recompile your code.</p>
  593. </div>
  594. <hr width="100%">
  595. <h2>Conclusion</h2>
  596. <div style="margin-left: 2em">
  597. <p>There are two key concepts that this article has introduced:</p>
  598. <ul>
  599. <li>The use of a generic requirements based approach to simplify and
  600. adapt the use of the C<font size="-1">OUNTED</font> B<font size=
  601. "-1">ODY</font> pattern.</li>
  602. <li>The ability, through control of allocation, to dynamically and
  603. non-intrusively add capabilities to fixed types using the R<font size=
  604. "-1">UNTIME</font> M<font size="-1">IXIN</font> pattern.</li>
  605. </ul>
  606. <p>The application of the two together gives rise to a new variant of the
  607. essential C<font size="-1">OUNTED</font> B<font size="-1">ODY</font>
  608. pattern, U<font size="-1">NINTRUSIVE</font> C<font size=
  609. "-1">OUNTED</font> B<font size="-1">ODY</font>. You can take this theme
  610. even further and contrive a simple garbage collection system for C++.</p>
  611. <p>The complete code for <tt><font size="+1">countable_ptr</font></tt>,
  612. <tt><font size="+1">countability</font></tt>, and the <tt><font size=
  613. "+1">countable new</font></tt> is also available.</p>
  614. </div>
  615. <div align="right">
  616. <hr width="100%">
  617. <font size="-1"><i>First published in</i> <a href=
  618. "http://www.accu.org/c++sig/public/Overload.html">Overload</a> <i>25,
  619. April 1998, ISSN 1354-3172</i></font>
  620. </div>
  621. <p><a href="http://validator.w3.org/check?uri=referer"><img border="0" src=
  622. "http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01 Transitional"
  623. height="31" width="88"></a></p>
  624. <p>Revised
  625. <!--webbot bot="Timestamp" s-type="EDITED" s-format="%d %B, %Y" startspan -->04 December, 2006<!--webbot bot="Timestamp" endspan i-checksum="38514" --></p>
  626. <p><i>Copyright &copy; 1998-1999 Kevlin Henney</i></p>
  627. <p><i>Distributed under the Boost Software License, Version 1.0. (See
  628. accompanying file <a href="../LICENSE_1_0.txt">LICENSE_1_0.txt</a> or copy
  629. at <a href=
  630. "http://www.boost.org/LICENSE_1_0.txt">http://www.boost.org/LICENSE_1_0.txt</a>)</i></p>
  631. </body>
  632. </html>
粤ICP备19079148号