generic_exception_safety.html 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2. <!-- saved from url=(0052)http://people.ne.mediaone.net/abrahams/abrahams.html -->
  3. <meta name="generator" content="Microsoft FrontPage 5.0">
  4. <title>Exception-Safety in Generic Components</title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
  6. <meta content="MSHTML 5.50.4522.1800" name="GENERATOR">
  7. <h1 align="center">Exception-Safety in Generic Components</h1>
  8. <p align="center"><i><b>Lessons Learned from Specifying Exception-Safety
  9. for the C++ Standard Library</b></i>
  10. <h3 align="center">David Abrahams</h3>
  11. <h3 align="center"><a href="mailto:david.abrahams@rcn.com">
  12. david.abrahams@rcn.com</a></h3>
  13. <p><b>Abstract.</b> This paper represents the knowledge accumulated in
  14. response to a real-world need: that the C++ Standard Template Library
  15. exhibit useful and well-defined interactions with exceptions, the
  16. error-handling mechanism built-in to the core C++ language. It explores the
  17. meaning of exception-safety, reveals surprising myths about exceptions and
  18. genericity, describes valuable tools for reasoning about program
  19. correctness, and outlines an automated testing procedure for verifying
  20. exception-safety.
  21. <p><b>Keywords:</b> exception-safety, exceptions, STL, C++
  22. <h2>1 What is exception-safety?</h2>
  23. <p>Informally, exception-safety in a component means that it exhibits
  24. reasonable behavior when an exception is thrown during its execution. For
  25. most people, the term ``reasonable'' includes all the usual
  26. expectations for error-handling: that resources should not be leaked, and
  27. that the program should remain in a well-defined state so that execution
  28. can continue. For most components, it also includes the expectation that
  29. when an error is encountered, it is reported to the caller.
  30. <p>More formally, we can describe a component as minimally exception-safe
  31. if, when exceptions are thrown from within that component, its invariants
  32. are intact. Later on we'll see that at least three different levels of
  33. exception-safety can be usefully distinguished. These distinctions can help
  34. us to describe and reason about the behavior of large systems.
  35. <p>In a generic component, we usually have an additional expectation of
  36. <i>exception-neutrality</i>, which means that exceptions thrown by a
  37. component's type parameters should be propagated, unchanged, to the
  38. component's caller.
  39. <h2>2 Myths and Superstitions</h2>
  40. <p>Exception-safety seems straightforward so far: it doesn't constitute
  41. anything more than we'd expect from code using more traditional
  42. error-handling techniques. It might be worthwhile, however, to examine the
  43. term from a psychological viewpoint. Nobody ever spoke of
  44. ``error-safety'' before C++ had exceptions.
  45. <p>It's almost as though exceptions are viewed as a <i>mysterious
  46. attack</i> on otherwise correct code, from which we must protect ourselves.
  47. Needless to say, this doesn't lead to a healthy relationship with error
  48. handling! During standardization, a democratic process which requires broad
  49. support for changes, I encountered many widely-held superstitions. In order
  50. to even begin the discussion of exception-safety in generic components, it
  51. may be worthwhile confronting a few of them.
  52. <p><i>``Interactions between templates and exceptions are not
  53. well-understood.''</i> This myth, often heard from those who consider
  54. these both new language features, is easily disposed of: there simply are
  55. no interactions. A template, once instantiated, works in all respects like
  56. an ordinary class or function. A simple way to reason about the behavior of
  57. a template with exceptions is to think of how a specific instantiation of
  58. that template works. Finally, the genericity of templates should not cause
  59. special concern. Although the component's client supplies part of the
  60. operation (which may, unless otherwise specified, throw arbitrary
  61. exceptions), the same is true of operations using familiar virtual
  62. functions or simple function pointers.
  63. <p><i>``It is well known to be impossible to write an exception-safe
  64. generic container.''</i> This claim is often heard with reference to
  65. an article by Tom Cargill <a title=
  66. "Tom Cargill, ``Exception Handling: A False Sense of Security'', C++ Report, Nov-Dec 1994"
  67. href=
  68. "#reference4"><sup>[4]</sup></a>
  69. in which he explores the problem of exception-safety for a generic stack
  70. template. In his article, Cargill raises many useful questions, but
  71. unfortunately fails to present a solution to his problem.<a title=
  72. "Probably the greatest impediment to a solution in Cargill's case was an unfortunate combination of choices on his part: the interface he chose for his container was incompatible with his particular demands for safety. By changing either one he might have solved the problem."
  73. href=
  74. "#footnote1"><sup>1</sup></a>
  75. He concludes by suggesting that a solution may not be possible.
  76. Unfortunately, his article was read by many as ``proof'' of that
  77. speculation. Since it was published there have been many examples of
  78. exception-safe generic components, among them the C++ standard library
  79. containers.
  80. <p><i>``Dealing with exceptions will slow code down, and templates are
  81. used specifically to get the best possible performance.''</i> A good
  82. implementation of C++ will not devote a single instruction cycle to dealing
  83. with exceptions until one is thrown, and then it can be handled at a speed
  84. comparable with that of calling a function <a title=
  85. "D. R. Musser, ``Introspective Sorting and Selection Algorithms'', Software-Practice and Experience 27(8):983-993, 1997."
  86. href=
  87. "#reference7"><sup>[7]</sup></a>.
  88. That alone gives programs using exceptions performance equivalent to that
  89. of a program which ignores the possibility of errors. Using exceptions can
  90. actually result in faster programs than ``traditional'' error
  91. handling methods for other reasons. First, a catch block clearly indicates
  92. to the compiler which code is devoted to error-handling; it can then be
  93. separated from the usual execution path, improving locality of reference.
  94. Second, code using ``traditional'' error handling must typically
  95. test a return value for errors after every single function call; using
  96. exceptions completely eliminates that overhead.
  97. <p><i>``Exceptions make it more difficult to reason about a program's
  98. behavior.''</i> Usually cited in support of this myth is the way
  99. ``hidden'' execution paths are followed during stack-unwinding.
  100. Hidden execution paths are nothing new to any C++ programmer who expects
  101. local variables to be destroyed upon returning from a function:
  102. <blockquote>
  103. <pre>ErrorCode f( int&amp; result ) // 1
  104. { // 2
  105. X x; // 3
  106. ErrorCode err = x.g( result ); // 4
  107. if ( err != kNoError ) // 5
  108. return err; // 6
  109. // ...More code here...
  110. return kNoError; // 7
  111. }
  112. </pre>
  113. </blockquote>
  114. <p>In the example above, there is a ``hidden'' call to
  115. <code>X::~X()</code> in lines 6 and 7. Granted, using exceptions, there is
  116. no code devoted to error handling visible:
  117. <blockquote>
  118. <pre>int f() // 1
  119. { // 2
  120. X x; // 3
  121. int result = x.g(); // 4
  122. // ...More code here...
  123. return result; // 5
  124. }
  125. </pre>
  126. </blockquote>
  127. <p>For many programmers more familiar with exceptions, the second example
  128. is actually more readable and understandable than the first. The
  129. ``hidden'' code paths include the same calls to destructors of
  130. local variables. In addition, they follow a simple pattern which acts
  131. <i>exactly</i> as though there were a potential return statement after each
  132. function call in case of an exception. Readability is enhanced because the
  133. normal path of execution is unobscured by error-handling, and return values
  134. are freed up to be used in a natural way.
  135. <p>There is an even more important way in which exceptions can enhance
  136. correctness: by allowing simple class invariants. In the first example, if
  137. <code>x</code>'s constructor should need to allocate resources, it has no
  138. way to report a failure: in C++, constructors have no return values. The
  139. usual result when exceptions are avoided is that classes requiring
  140. resources must include a separate initializer function which finishes the
  141. job of construction. The programmer can therefore never be sure, when an
  142. object of class <code>X</code> is used, whether he is handling a
  143. full-fledged <code>X</code> or some abortive attempt to construct one (or
  144. worse: someone simply forgot to call the initializer!)
  145. <h2>3 A contractual basis for exception-safety</h2>
  146. <p>A non-generic component can be described as exception-safe in isolation,
  147. but because of its configurability by client code, exception-safety in a
  148. generic component usually depends on a contract between the component and
  149. its clients. For example, the designer of a generic component might require
  150. that an operation which is used in the component's destructor not throw any
  151. exceptions.<a title=
  152. " It is usually inadvisable to throw an exception from a destructor in C++, since the destructor may itself be called during the stack-unwinding caused by another exception. If the second exception is allowed to propagate beyond the destructor, the program is immediately terminated."
  153. href=
  154. "#footnote2"><sup>2</sup></a>
  155. The generic component might, in return, provide one of the following
  156. guarantees:
  157. <ul>
  158. <li>The <i>basic</i> guarantee: that the invariants of the component are
  159. preserved, and no resources are leaked.
  160. <li>The <i>strong</i> guarantee: that the operation has either completed
  161. successfully or thrown an exception, leaving the program state exactly as
  162. it was before the operation started.
  163. <li>The <i>no-throw</i> guarantee: that the operation will not throw an
  164. exception.
  165. </ul>
  166. <p>The basic guarantee is a simple minimum standard for exception-safety to
  167. which we can hold all components. It says simply that after an exception,
  168. the component can still be used as before. Importantly, the preservation of
  169. invariants allows the component to be destroyed, potentially as part of
  170. stack-unwinding. This guarantee is actually less useful than it might at
  171. first appear. If a component has many valid states, after an exception we
  172. have no idea what state the component is in|only that the state is valid.
  173. The options for recovery in this case are limited: either destruction or
  174. resetting the component to some known state before further use. Consider
  175. the following example:
  176. <blockquote>
  177. <pre>template &lt;class X&gt;
  178. void print_random_sequence()
  179. {
  180. std::vector&lt;X&gt; v(10); // A vector of 10 items
  181. try {
  182. // Provides only the <i>basic</i> guarantee
  183. v.insert( v.begin(), X() );
  184. }
  185. catch(...) {} // ignore any exceptions above
  186. // print the vector's contents
  187. std::cout "(" &lt;&lt; v.size() &lt;&lt; ") ";
  188. std::copy( v.begin(), v.end(),
  189. std::ostream_iterator&lt;X&gt;( std::cout, " " ) );
  190. }
  191. </pre>
  192. </blockquote>
  193. <p>Since all we know about v after an exception is that it is valid, the
  194. function is allowed to print any random sequence of <code>X</code>s.<a
  195. title=
  196. "In practice of course, this function would make an extremely poor random sequence generator!"
  197. href=
  198. "#footnote3"><sup>3</sup></a>
  199. It is ``safe'' in the sense that it is not allowed to crash, but
  200. its output may be unpredictable.
  201. <p>The <i>strong</i> guarantee provides full
  202. ``commit-or-rollback'' semantics. In the case of C++ standard
  203. containers, this means, for example, that if an exception is thrown all
  204. iterators remain valid. We also know that the container has exactly the
  205. same elements as before the exception was thrown. A transaction that has no
  206. effects if it fails has obvious benefits: the program state is simple and
  207. predictable in case of an exception. In the C++ standard library, nearly
  208. all of the operations on the node-based containers list, set, multiset,
  209. map, and multimap provide the <i>strong</i> guarantee.<a title=
  210. "It is worth noting that mutating algorithms usually cannot provide the strong guarantee: to roll back a modified element of a range, it must be set back to its previous value using operator=, which itself might throw. In the C++ standard library, there are a few exceptions to this rule, whose rollback behavior consists only of destruction: uninitialized_copy, uninitialized_fill, and uninitialized_fill_n."
  211. href=
  212. "#footnote4"><sup>4</sup></a>).
  213. <p>The <i>no-throw</i> guarantee is the strongest of all, and it says that
  214. an operation is guaranteed not to throw an exception: it always completes
  215. successfully. This guarantee is necessary for most destructors, and indeed
  216. the destructors of C++ standard library components are all guaranteed not
  217. to throw exceptions. The <i>no-throw</i> guarantee turns out to be
  218. important for other reasons, as we shall see.<a title=
  219. "All type parameters supplied by clients of the C++ standard library are required not to throw from their destructors. In return, all components of the C++ standard library provide at least the basic guarantee."
  220. href=
  221. "#footnote5"><sup>5</sup></a>
  222. <h2>4 Legal Wrangling</h2>
  223. <p>Inevitably, the contract can get more complicated: a quid pro quo
  224. arrangement is possible. Some components in the C++ Standard Library give
  225. one guarantee for arbitrary type parameters, but give a stronger guarantee
  226. in exchange for additional promises from the client type that no exceptions
  227. will be thrown. For example, the standard container operation
  228. <code>vector&lt;T&gt;::erase</code> gives the <i>basic</i> guarantee for
  229. any <code>T</code>, but for types whose copy constructor and copy
  230. assignment operator do not throw, it gives the <i>no-throw</i> guarantee.<a
  231. title=
  232. "Similar arrangements might have been made in the C++ standard for many of the mutating algorithms, but were never considered due to time constraints on the standardization process."
  233. href=
  234. "#footnote6"><sup>6</sup></a>
  235. <h2>5 What level of exception-safety should a component specify?</h2>
  236. <p>From a client's point-of-view, the strongest possible level of safety
  237. would be ideal. Of course, the <i>no-throw</i> guarantee is simply
  238. impossible for many operations, but what about the <i>strong</i> guarantee?
  239. For example, suppose we wanted atomic behavior for
  240. <code>vector&lt;T&gt;::insert</code>. Insertion into the middle of a vector
  241. requires copying elements after the insertion point into later positions,
  242. to make room for the new element. If copying an element can fail, rolling
  243. back the operation would require ``undoing'' the previous
  244. copies...which depends on copying again. If copying back should fail (as it
  245. likely would), we have failed to meet our guarantee.
  246. <p>One possible alternative would be to redefine <code>insert</code> to
  247. build the new array contents in a fresh piece of memory each time, and only
  248. destroy the old contents when that has succeeded. Unfortunately, there is a
  249. non-trivial cost if this approach is followed: insertions near the end of a
  250. vector which might have previously caused only a few copies would now cause
  251. every element to be copied. The <i>basic</i> guarantee is a
  252. ``natural'' level of safety for this operation, which it can
  253. provide without violating its performance guarantees. In fact all of the
  254. operations in the library appear to have such a ``natural'' level
  255. of safety.
  256. <p>Because performance requirements were already a well-established part of
  257. the draft standard and because performance is a primary goal of the STL,
  258. there was no attempt to specify more safety than could be provided within
  259. those requirements. Although not all of the library gives the <i>strong</i>
  260. guarantee, almost any operation on a standard container which gives the
  261. <i>basic</i> guarantee can be made <i>strong</i> using the ``make a
  262. new copy'' strategy described above:
  263. <blockquote>
  264. <pre>template &lt;class Container, class BasicOp&gt;
  265. void MakeOperationStrong( Container&amp; c, const BasicOp&amp; op )
  266. {
  267. Container tmp(c); // Copy c
  268. op(tmp); // Work on the copy
  269. c.swap(tmp); // Cannot fail<a title=
  270. "Associative containers whose Compare object might throw an exception when copied cannot use this technique, since the swap function might fail."
  271. href=
  272. "#footnote7"><sup>7</sup></a>
  273. }
  274. </pre>
  275. </blockquote>
  276. <p>This technique can be folded into a wrapper class to make a similar
  277. container which provides stronger guarantees (and different performance
  278. characteristics).<a title=
  279. "This suggests another potential use for the oft-wished-for but as yet unseen container traits&lt;&gt; template: automated container selection to meet exceptionsafety constraints."
  280. href=
  281. "#footnote8"><sup>8</sup></a>
  282. <h2>6 Should we take everything we can get?</h2>
  283. <p>By considering a particular implementation, we can hope to discern a
  284. natural level of safety. The danger in using this to establish requirements
  285. for a component is that the implementation might be restricted. If someone
  286. should come up with a more-efficient implementation which we'd like to use,
  287. we may find that it's incompatible with our exception-safety requirements.
  288. One might expect this to be of no concern in the well-explored domains of
  289. data structures and algorithms covered by the STL, but even there, advances
  290. are being made. A good example is the recent <i>introsort</i> algorithm <a
  291. title=
  292. "D. R. Musser, ``Introspective Sorting and Selection Algorithms'', Software-Practice and Experience 27(8):983-993, 1997."
  293. href=
  294. "#reference6"><sup>[6]</sup></a>,
  295. which represents a substantial improvement in worst-case complexity over
  296. the well-established <i>quicksort</i>.
  297. <p>To determine exactly how much to demand of the standard components, I
  298. looked at a typical real-world scenario. The chosen test case was a
  299. ``composite container.'' Such a container, built of two or more
  300. standard container components, is not only commonly needed, but serves as a
  301. simple representative case for maintaining invariants in larger systems:
  302. <blockquote>
  303. <pre>// SearchableStack - A stack which can be efficiently searched
  304. // for any value.
  305. template &lt;class T&gt;
  306. class SearchableStack
  307. {
  308. public:
  309. void push(const T&amp; t); // O(log n)
  310. void pop(); // O(log n)
  311. bool contains(const T&amp; t) const; // O(log n)
  312. const T&amp; top() const; // O(1)
  313. private:
  314. std::set&lt;T&gt; set_impl;
  315. std::list&lt;std::set&lt;T&gt;::iterator&gt; list_impl;
  316. };
  317. </pre>
  318. </blockquote>
  319. <p>The idea is that the list acts as a stack of set iterators: every
  320. element goes into the set first, and the resulting position is pushed onto
  321. the list. The invariant is straightforward: the set and the list should
  322. always have the same number of elements, and every element of the set
  323. should be referenced by an element of the list. The following
  324. implementation of the push function is designed to give the <i>strong</i>
  325. guarantee within the natural levels of safety provided by set and list:
  326. <blockquote>
  327. <pre>template &lt;class T&gt; // 1
  328. void SearchableStack&lt;T&gt;::push(const T&amp; t) // 2
  329. { // 3
  330. set&lt;T&gt;::iterator i = set_impl.insert(t); // 4
  331. try // 5
  332. { // 6
  333. list_impl.push_back(i); // 7
  334. } // 8
  335. catch(...) // 9
  336. { // 10
  337. set_impl.erase(i); // 11
  338. throw; // 12
  339. } // 13
  340. } // 14
  341. </pre>
  342. </blockquote>
  343. <p>What does our code actually require of the library? We need to examine
  344. the lines where non-const operations occur:
  345. <ul>
  346. <li>Line 4: if the insertion fails but <code>set_impl</code> is modified
  347. in the process, our invariant is violated. We need to be able to rely on
  348. the <i>strong</i> guarantee from <code>set&lt;T&gt;::insert</code>.
  349. <li>Line 7: likewise, if <code>push_back</code> fails, but
  350. <code>list_impl</code> is modified in the process, our invariant is
  351. violated, so we need to be able to rely on the <i>strong</i> guarantee
  352. from list&lt;T&gt;::insert.
  353. <li>Line 11: here we are ``rolling back'' the insertion on line
  354. 4. If this operation should fail, we will be unable to restore our
  355. invariant. We absolutely depend on the <i>no-throw</i> guarantee from
  356. <code>set&lt;T&gt;::erase</code>.<a title=
  357. "One might be tempted to surround the erase operation with a try/catch block to reduce the requirements on set&lt;T&gt; and the problems that arise in case of an exception, but in the end that just begs the question. First, erase just failed and in this case there are no viable alternative ways to produce the necessary result. Second and more generally, because of the variability of its type parameters a generic component can seldom be assured that any alternatives will succeed."
  358. href=
  359. "#footnote9"><sup>9</sup></a>
  360. <li>Line 11: for the same reasons, we also depend on being able to pass
  361. the <code>i</code> to the <code>erase</code> function: we need the
  362. <i>no-throw</i> guarantee from the copy constructor of
  363. <code>set&lt;T&gt;::iterator</code>.
  364. </ul>
  365. <p>I learned a great deal by approaching the question this way during
  366. standardization. First, the guarantee specified for the composite container
  367. actually depends on stronger guarantees from its components (the
  368. <i>no-throw</i> guarantees in line 11). Also, I took advantage of all of
  369. the natural level of safety to implement this simple example. Finally, the
  370. analysis revealed a requirement on iterators which I had previously
  371. overlooked when operations were considered on their own. The conclusion was
  372. that we should provide as much of the natural level of safety as possible.
  373. Faster but less-safe implementations could always be provided as extensions
  374. to the standard components. <sup><a title=
  375. "The prevalent philosophy in the design of STL was that functionality that wasn't essential to all uses should be left out in favor of efficiency, as long as that functionality could be obtained when needed by adapting the base components. This departs from that philosophy, but it would be difficult or impossible to obtain even the basic guarantee by adapting a base component that doesn't already have it."
  376. name="#footnote10">10</a></sup>
  377. <h2>7 Automated testing for exception-safety</h2>
  378. <p>As part of the standardization process, I produced an exception-safe
  379. reference implementation of the STL. Error-handling code is seldom
  380. rigorously tested in real life, in part because it is difficult to cause
  381. error conditions to occur. It is very common to see error-handling code
  382. which crashes the first time it is executed ...in a shipping product! To
  383. bolster confidence that the implementation actually worked as advertised, I
  384. designed an automated test suite, based on an exhaustive technique due to
  385. my colleague Matt Arnold.
  386. <p>The test program started with the basics: reinforcement and
  387. instrumentation, especially of the global operators <code>new</code> and
  388. <code>delete</code>.<sup><a title=
  389. "An excellent discussion on how to fortify memory subsystems can be found in: Steve Maguire, Writing Solid Code, Microsoft Press, Redmond, WA, 1993, ISBN 1-55615- 551-4."
  390. name="#footnote11">11</a></sup>Instances of the components (containers and
  391. algorithms) were created, with type parameters chosen to reveal as many
  392. potential problems as possible. For example, all type parameters were given
  393. a pointer to heap-allocated memory, so that leaking a contained object
  394. would be detected as a memory leak.
  395. <p>Finally, a scheme was designed that could cause an operation to throw an
  396. exception at each possible point of failure. At the beginning of every
  397. client-supplied operation which is allowed to throw an exception, a call to
  398. <code>ThisCanThrow</code> was added. A call to <code>ThisCanThrow</code>
  399. also had to be added everywhere that the generic operation being tested
  400. might throw an exception, for example in the global operator
  401. <code>new</code>, for which an instrumented replacement was supplied.
  402. <blockquote>
  403. <pre>// Use this as a type parameter, e.g. vector&lt;TestClass&gt;
  404. struct TestClass
  405. {
  406. TestClass( int v = 0 )
  407. : p( ThisCanThrow(), new int( v ) ) {}
  408. TestClass( const TestClass&amp; rhs )
  409. : p( ThisCanThrow(), new int( *rhs.p ) ) {}
  410. const TestClass&amp; operator=( const TestClass&amp; rhs )
  411. { ThisCanThrow(); *p = *rhs.p; }
  412. bool operator==( const TestClass&amp; rhs )
  413. { ThisCanThrow(); return *p == *rhs.p; }
  414. ...etc...
  415. ~TestClass() { delete p; }
  416. };
  417. </pre>
  418. </blockquote>
  419. <p><code>ThisCanThrow</code> simply decrements a ``throw
  420. counter'' and, if it has reached zero, throws an exception. Each test
  421. takes a form which begins the counter at successively higher values in an
  422. outer loop and repeatedly attempts to complete the operation being tested.
  423. The result is that the operation throws an exception at each successive
  424. step along its execution path that can possibly fail. For example, here is
  425. a simplified version of the function used to test the <i>strong</i>
  426. guarantee: <a title=
  427. "Note that this technique requires that the operation being tested be exception-neutral. If the operation ever tries to recover from an exception and proceed, the throw counter will be negative, and subsequent operations that might fail will not be tested for exception-safety."
  428. href=
  429. "#footnote12"><sup>12</sup></a>
  430. <blockquote>
  431. <pre>extern int gThrowCounter; // The throw counter
  432. void ThisCanThrow()
  433. {
  434. if (gThrowCounter-- == 0)
  435. throw 0;
  436. }
  437. template &lt;class Value, class Operation&gt;
  438. void StrongCheck(const Value&amp; v, const Operation&amp; op)
  439. {
  440. bool succeeded = false;
  441. for (long nextThrowCount = 0; !succeeded; ++nextThrowCount)
  442. {
  443. Value duplicate = v;
  444. try
  445. {
  446. gThrowCounter = nextThrowCount;
  447. op( duplicate ); // Try the operation
  448. succeeded = true;
  449. }
  450. catch(...) // Catch all exceptions
  451. {
  452. bool unchanged = duplicate == v; // Test <i>strong</i> guarantee
  453. assert( unchanged );
  454. }
  455. // Specialize as desired for each container type, to check
  456. // integrity. For example, size() == distance(begin(),end())
  457. CheckInvariant(v); // Check any invariant
  458. }
  459. }
  460. </pre>
  461. </blockquote>
  462. <p>Notably, this kind of testing is much easier and less intrusive with a
  463. generic component than with non-generics, because testing-specific type
  464. parameters can be used without modifying the source code of the component
  465. being tested. Also, generic functions like <code>StrongCheck</code> above
  466. were instrumental in performing the tests on a wide range of values and
  467. operations.
  468. <h2>8 Further Reading</h2>
  469. To my knowledge, there are currently only two descriptions of STL
  470. exception-safety available. The original specification <a title=
  471. "D. Abrahams, Exception Safety in STLport" href=
  472. "#reference2"><sup>[2]</sup></a>
  473. for the reference exception-safe implementation of the STL is an informal
  474. specification, simple and self-explanatory (also verbose), and uses the
  475. <i>basic-</i> and <i>strong-</i>guarantee distinctions outlined in this
  476. article. It explicitly forbids leaks, and differs substantively from the
  477. final C++ standard in the guarantees it makes, though they are largely
  478. identical. I hope to produce an updated version of this document soon.
  479. <p>The description of exception-safety in the C++ Standard <a title=
  480. "International Standard ISO/IEC 14882, Information Technology-Programming Languages-C++, Document Number ISO/IEC 14882-1998"
  481. href=
  482. "#reference1"><sup>[1]</sup></a>
  483. is only slightly more formal, but relies on hard-to-read
  484. ``standardese'' and an occasionally subtle web of implication.<a
  485. title=
  486. "The changes to the draft standard which introduced exception-safety were made late in the process, when amendments were likely to be rejected solely on the basis of the number of altered words. Unfortunately, the result compromises clarity somewhat in favor of brevity. Greg Colvin was responsible for the clever language-lawyering needed to minimize the extent of these changes."
  487. href=
  488. "#footnote13"><sup>13</sup></a>
  489. In particular, leaks are not treated directly at all. It does have the
  490. advantage that it <i>is</i> the standard.
  491. <p>The original reference implementation <a title=
  492. "B. Fomitchev, Adapted SGI STL Version 1.0, with exception handling code by D. Abrahams"
  493. href=
  494. "#reference5"><sup>[5]</sup></a>
  495. of the exception-safe STL is an adaptation of an old version of the SGI
  496. STL, designed for C++ compilers with limited features. Although it is not a
  497. complete STL implementation, the code may be easier to read, and it
  498. illustrates a useful base-class technique for eliminating
  499. exception-handling code in constructors. The full test suite <a title=
  500. "D. Abrahams and B. Fomitchev, Exception Handling Test Suite" href=
  501. "#reference3"><sup>[3]</sup></a>
  502. used to validate the reference implementation has been used successfully to
  503. validate all recent versions of the SGI STL, and has been adapted to test
  504. one other vendor's implementation (which failed). As noted on the
  505. documentation page, it also seems to have the power to reveal hidden
  506. compiler bugs, particularly where optimizers interact with
  507. exception-handling code.
  508. <h2>References</h2>
  509. <ol>
  510. <li><a name="reference1">International</a> Standard ISO/IEC 14882,
  511. <i>Information Technology-Programming Languages-C++</i>, Document Number
  512. ISO/IEC 14882-1998, available from <a href=
  513. "http://webstore.ansi.org/ansidocstore/default.asp">http://webstore.ansi.org/ansidocstore/default.asp</a>.
  514. <li><a name="reference2">D.</a> Abrahams, <i>Exception Safety in
  515. STLport</i>, available at <a href=
  516. "http://www.stlport.org/doc/exception_safety.html">http://www.stlport.org/doc/exception_safety.html</a>.
  517. <li><a name="reference3">D.</a> Abrahams and B. Fomitchev, <i>Exception
  518. Handling Test Suite</i>, available at <a href=
  519. "http://www.stlport.org/doc/eh_testsuite.html">http://www.stlport.org/doc/eh_testsuite.html</a>.
  520. <li><a name="reference4">Tom</a> Cargill, ``Exception Handling:
  521. A False Sense of Security,'' C++ Report, Nov-Dec 1994, also
  522. available at <a href=
  523. "http://www.awprofessional.com/content/images/020163371x/supplements/Exception_Handling_Article.html">http://www.awprofessional.com/content/images/020163371x/supplements/Exception_Handling_Article.html</a>.
  524. <li><a name="reference5">B.</a> Fomitchev, <i>Adapted SGI STL Version
  525. 1.0</i>, with exception handling code by D. Abrahams, available at <a
  526. href=
  527. "http://www.metabyte.com/~fbp/stl/old.html">http://www.metabyte.com/~fbp/stl/old.html</a>.
  528. <li><a name="reference6">D.</a> R. Musser, ``Introspective Sorting
  529. and Selection Algorithms,'' <i>Software-Practice and Experience</i>
  530. 27(8):983-993, 1997.
  531. <li><a name="reference7">Bjarne</a> Stroustrup, <i>The Design And
  532. Evolution of C++</i>. Addison Wesley, Reading, MA, 1995, ISBN
  533. 0-201-54330-3, Section 16.9.1.
  534. </ol>
  535. <h2>Footnotes</h2>
  536. <p><a name="footnote1">1</a> Probably the greatest impediment to a solution
  537. in Cargill's case was an unfortunate combination of choices on his part:
  538. the interface he chose for his container was incompatible with his
  539. particular demands for safety. By changing either one he might have solved
  540. the problem.
  541. <p><a name="footnote2">2</a> It is usually inadvisable to throw an
  542. exception from a destructor in C++, since the destructor may itself be
  543. called during the stack-unwinding caused by another exception. If the
  544. second exception is allowed to propagate beyond the destructor, the program
  545. is immediately terminated.
  546. <p><a name="footnote3">3</a> In practice of course, this function would
  547. make an extremely poor random sequence generator!
  548. <p><a name="footnote4">4</a> It is worth noting that mutating algorithms
  549. usually cannot provide the <i>strong</i> guarantee: to roll back a modified
  550. element of a range, it must be set back to its previous value using
  551. <code>operator=</code>, which itself might throw. In the C++ standard
  552. library, there are a few exceptions to this rule, whose rollback behavior
  553. consists only of destruction: <code>uninitialized_copy</code>,
  554. <code>uninitialized_fill</code>, and <code>uninitialized_fill_n</code>.
  555. <p><a name="footnote5">5</a> All type parameters supplied by clients of the
  556. C++ standard library are required not to throw from their destructors. In
  557. return, all components of the C++ standard library provide at least the
  558. <i>basic</i> guarantee.
  559. <p><a name="footnote6">6</a> Similar arrangements might have been made in
  560. the C++ standard for many of the mutating algorithms, but were never
  561. considered due to time constraints on the standardization process.
  562. <p><a name="footnote7">7</a> Associative containers whose
  563. <code>Compare</code> object might throw an exception when copied cannot use
  564. this technique, since the swap function might fail.
  565. <p><a name="footnote8">8</a> This suggests another potential use for the
  566. oft-wished-for but as yet unseen <code>container_traits&lt;&gt;</code>
  567. template: automated container selection to meet exception-safety
  568. constraints.
  569. <p><a name="footnote9">9</a> One might be tempted to surround the erase
  570. operation with a <code>try</code>/<code>catch</code> block to reduce the
  571. requirements on <code>set&lt;T&gt;</code> and the problems that arise in
  572. case of an exception, but in the end that just begs the question. First,
  573. erase just failed and in this case there are no viable alternative ways to
  574. produce the necessary result. Second and more generally, because of the
  575. variability of its type parameters a generic component can seldom be
  576. assured that any alternatives will succeed.
  577. <p><a name="footnote10">10</a> The prevalent philosophy in the design of
  578. STL was that functionality that wasn't essential to all uses should be left
  579. out in favor of efficiency, as long as that functionality could be obtained
  580. when needed by adapting the base components. This departs from that
  581. philosophy, but it would be difficult or impossible to obtain even the
  582. <i>basic</i> guarantee by adapting a base component that doesn't already
  583. have it.
  584. <p><a name="footnote11">11</a> An excellent discussion on how to fortify
  585. memory subsystems can be found in: Steve Maguire, Writing Solid Code,
  586. Microsoft Press, Redmond, WA, 1993, ISBN 1-55615- 551-4.
  587. <p><a name="footnote12">12</a> Note that this technique requires that the
  588. operation being tested be exception-neutral. If the operation ever tries to
  589. recover from an exception and proceed, the throw counter will be negative,
  590. and subsequent operations that might fail will not be tested for
  591. exception-safety.
  592. <p><a name="footnote13">13</a> The changes to the draft standard which
  593. introduced exception-safety were made late in the process, when amendments
  594. were likely to be rejected solely on the basis of the number of altered
  595. words. Unfortunately, the result compromises clarity somewhat in favor of
  596. brevity. Greg Colvin was responsible for the clever language-lawyering
  597. needed to minimize the extent of these changes.
粤ICP备19079148号