count_bdy.htm 25 KB

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