More C++ Idioms/Detached Counted Body
From Wikibooks, the open-content textbooks collection
Contents |
[edit]
Detached Counted Body/Reference Counting (non-intrusive)
[edit] Intent
Adding reference counting to an object to which a reference count cannot directly be added.
[edit] Also Known As
- Reference Counting (non-intrusive)
- Detached Counted Body
[edit] Motivation
Some times Counted Body idiom can't be applied to certain classes when their sources are not available. We might only have object code and a header file. Detached Counted Body or non-intrusive reference counting can be used in such cases to prevent expensive copies of bodies.
[edit] Solution and Sample Code
Associate both a shared count, and a separate shared body, with each instance of a common handle abstraction:
class String { public: String(): rep(new char[1]), count(new int(1)) { rep[0] = '\0'; } String(const String &s): rep(s.rep), count(s.count) { (*count)++; } String &operator=(const String &s) { String temp(s); this->swap(temp); return *this; } void swap (String & s) throw () { std::swap (this->count, s.count); std::swap (this->rep, s.rep); } ~String() { if(--*count <= 0) { delete [] rep; delete count; } } String(const char *s): count(new int(1)), rep(new char[strlen(s)+1]) { strcpy(rep,s); } . . . . private: char *rep; int *count; }; int main() { String a = "hello", b = "world"; a = b; return 0; }
[edit] Consequences
Handles are slightly more expensive to copy than in Counted Body, memory fragmentation may increase, and initial construction overhead is higher because we are allocating multiple blocks.
[edit] Known Uses
- boost::shared_ptr
- ACE_Refcounted_Auto_Ptr
[edit] Related Idioms
[edit] References
http://users.rcn.com/jcoplien/Patterns/C++Idioms/EuroPLoP98.html#DetachedCountedBody
[edit] Copyright
Copyright ©1998 Lucent Technologies, Bell Labs Innovations. All rights reserved. Permission granted to reprint verbatim for non-commercial use provided this copyright notice appears. (Contents modified and enhanced for Wikibooks)