tracking_ptr.qbk 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. [/
  2. / Copyright (c) 2008 Eric Niebler
  3. /
  4. / Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. /]
  7. [section Cycle collection with [^tracking_ptr<>]]
  8. In xpressive, regex objects can refer to each other and themselves by value or by reference.
  9. In addition, they ref-count their referenced regexes to keep them alive. This creates the possibility
  10. for cyclic reference counts, and raises the possibility of memory leaks. xpressive avoids leaks
  11. by using a type called `tracking_ptr<>`. This doc describes at a high level how `tracking_ptr<>`
  12. works.
  13. [h2 Constraints]
  14. Our solution must meet the following design constraints:
  15. * No dangling references: All objects referred to directly or indirectly must be kept alive
  16. as long as the references are needed.
  17. * No leaks: all objects must be freed eventually.
  18. * No user intervention: The solution must not require users to explicitly invoke some cycle
  19. collection routine.
  20. * Clean-up is no-throw: The collection phase will likely be called from a destructor, so it
  21. must never throw an exception under any circumstance.
  22. [h2 Handle-Body Idiom]
  23. To use `tracking_ptr<>`, you must separate your type into a handle and a body. In the case of
  24. xpressive, the handle type is called `basic_regex<>` and the body is called `regex_impl<>`. The
  25. handle will store a `tracking_ptr<>` to the body.
  26. The body type must inherit from `enable_reference_tracking<>`. This gives the body the bookkeeping
  27. data structures that `tracking_ptr<>` will use. In particular, it gives the body:
  28. # `std::set<shared_ptr<body> > refs_` : collection of bodies to which this body refers, and
  29. # `std::set<weak_ptr<body> > deps_` : collection of bodies which refer to this body.
  30. [h2 References and Dependencies]
  31. We refer to (1) above as the "references" and (2) as the "dependencies". It is crucial to the
  32. understanding of `tracking_ptr<>` to recognize that the set of references includes both those
  33. objects that are referred to directly as well as those that are referred to indirectly (that
  34. is, through another reference). The same is true for the set of dependencies. In other words,
  35. each body holds a ref-count directly to every other body that it needs.
  36. Why is this important? Because it means that when a body no longer has a handle referring
  37. to it, all its references can be released immediately without fear of creating dangling references.
  38. References and dependencies cross-pollinate. Here's how it works:
  39. # When one object acquires another as a reference, the second object acquires the first as
  40. a dependency.
  41. # In addition, the first object acquires all of the second object's references, and the second
  42. object acquires all of the first object's dependencies.
  43. # When an object picks up a new reference, the reference is also added to all dependent objects.
  44. # When an object picks up a new dependency, the dependency is also added to all referenced
  45. objects.
  46. # An object is never allowed to have itself as a dependency. Objects may have themselves as
  47. references, and often do.
  48. Consider the following code:
  49. sregex expr;
  50. {
  51. sregex group = '(' >> by_ref(expr) >> ')'; // (1)
  52. sregex fact = +_d | group; // (2)
  53. sregex term = fact >> *(('*' >> fact) | ('/' >> fact)); // (3)
  54. expr = term >> *(('+' >> term) | ('-' >> term)); // (4)
  55. } // (5)
  56. Here is how the references and dependencies propagate, line by line:
  57. [table
  58. [[Expression][Effects]]
  59. [[1) `sregex group = '(' >> by_ref(expr) >> ')';`]
  60. [[^group: cnt=1 refs={expr} deps={}\n
  61. expr: cnt=2 refs={} deps={group}]]]
  62. [[2) `sregex fact = +_d | group;`]
  63. [[^group: cnt=2 refs={expr} deps={fact}\n
  64. expr: cnt=3 refs={} deps={group,fact}\n
  65. fact: cnt=1 refs={expr,group} deps={}]]]
  66. [[3) `sregex term = fact >> *(('*' >> fact) | ('/' >> fact));`]
  67. [[^group: cnt=3 refs={expr} deps={fact,term}\n
  68. expr: cnt=4 refs={} deps={group,fact,term}\n
  69. fact: cnt=2 refs={expr,group} deps={term}\n
  70. term: cnt=1 refs={expr,group,fact} deps={}]]]
  71. [[4) `expr = term >> *(('+' >> term) | ('-' >> term));`]
  72. [[^group: cnt=5 refs={expr,group,fact,term} deps={expr,fact,term}\n
  73. expr: cnt=5 refs={expr,group,fact,term} deps={group,fact,term}\n
  74. fact: cnt=5 refs={expr,group,fact,term} deps={expr,group,term}\n
  75. term: cnt=5 refs={expr,group,fact,term} deps={expr,group,fact}]]]
  76. [[5) `}`]
  77. [[^expr: cnt=2 refs={expr,group,fact,term} deps={group,fact,term}]]]
  78. ]
  79. This shows how references and dependencies propagate when creating cycles of objects. After
  80. line (4), which closes the cycle, every object has a ref-count on every other object, even
  81. to itself. So how does this not leak? Read on.
  82. [h2 Cycle Breaking]
  83. Now that the bodies have their sets of references and dependencies, the hard part is done.
  84. All that remains is to decide when and where to break the cycle. That is the job of `tracking_ptr<>`,
  85. which is part of the handle. The `tracking_ptr<>` holds 2 `shared_ptr`s. The first, obviously,
  86. is the `shared_ptr<body>` -- the reference to the body to which this handle refers. The other
  87. `shared_ptr` is used to break the cycle. It ensures that when all the handles to a body go out
  88. of scope, the body's set of references is cleared.
  89. This suggests that more than one handle can refer to a body. In fact, `tracking_ptr<>` gives
  90. you copy-on-write semantics -- when you copy a handle, the body is shared. That makes copies
  91. very efficient. Eventually, all the handles to a particular body go out of scope. When that
  92. happens, the ref count to the body might still be greater than 0 because some other body (or
  93. this body itself!) might be holding a reference to it. However, we are certain that the cycle-breaker's
  94. ref-count goes to 0 because the cycle-breaker only lives in handles. No more handles, no more
  95. cycle-breakers.
  96. What does the cycle-breaker do? Recall that the body has a set of references of type
  97. `std::set<shared_ptr<body> >`. Let's call this type "references_type". The cycle-breaker is a
  98. `shared_ptr<references_type>`. It uses a custom deleter, which is defined as follows:
  99. template<typename DerivedT>
  100. struct reference_deleter
  101. {
  102. void operator ()(std::set<shared_ptr<DerivedT> > *refs) const
  103. {
  104. refs->clear();
  105. }
  106. };
  107. The job of to the cycle breaker is to ensure that when the last handle to a body goes away,
  108. the body's set of references is cleared. That's it.
  109. We can clearly see how this guarantees that all bodies are cleaned up eventually. Once every
  110. handle has gone out of scope, all the bodies' sets of references will be cleared, leaving none
  111. with a non-zero ref-count. No leaks, guaranteed.
  112. It's a bit harder to see how this guarantees no dangling references. Imagine that there are 3
  113. bodies: A, B and C. A refers to B which refers to C. Now all the handles to B go out of scope,
  114. so B's set of references is cleared. Doesn't this mean that C gets deleted, even though it
  115. is being used (indirectly) by A? It doesn't. This situation can never occur because we propagated
  116. the references and dependencies above such that A will be holding a reference directly to C
  117. in addition to B. When B's set of references is cleared, no bodies get deleted, because they
  118. are all still in use by A.
  119. [h2 Future Work]
  120. All these `std::set`s and `shared_ptr`s and `weak_ptr`s! Very inefficient. I used them because
  121. they were handy. I could probably do better.
  122. Also, some objects stick around longer than they need to. Consider:
  123. sregex b;
  124. {
  125. sregex a = _;
  126. b = by_ref(a);
  127. b = _;
  128. }
  129. // a is still alive here!
  130. Due to the way references and dependencies are propagated, the `std::set` of references can only
  131. grow. It never shrinks, even when some references are no longer needed. For xpressive this
  132. isn't an issue. The graphs of referential objects generally stay small and isolated. If someone
  133. were to try to use `tracking_ptr<>` as a general ref-count-cycle-collection mechanism, this problem
  134. would have to be addressed.
  135. [endsect]