--- /usr/include/boost/any.hpp 2009-02-26 05:16:09.000000000 -0700 +++ any.hpp 2009-04-04 14:27:10.034162766 -0700 @@ -34,16 +34,18 @@ any(const ValueType & value) : content(new holder(value)) { + content->add_ref(); } any(const any & other) - : content(other.content ? other.content->clone() : 0) + : content(other.content) { + if (content) content->add_ref(); } ~any() { - delete content; + if (content) content->rem_ref(); } public: // modifiers @@ -99,6 +101,20 @@ virtual placeholder * clone() const = 0; + public: // reference counting + + long references; + + void add_ref() + { + ++references; + } + + void rem_ref() + { + if (--references == 0) delete this; + } + }; template @@ -139,6 +155,18 @@ template friend ValueType * unsafe_any_cast(any *); + private: // reference counting + + void make_unique() const + { + if (content && content->references != 1) { + any* unconst = const_cast(this); + unconst->content->rem_ref(); + unconst->content = unconst->content->clone(); + unconst->content->add_ref(); + } + } + #else public: // representation (public so any_cast can be non-friend) @@ -162,6 +190,7 @@ template ValueType * any_cast(any * operand) { + operand->make_unique(); return operand && operand->type() == typeid(ValueType) ? &static_cast *>(operand->content)->held : 0; @@ -170,6 +199,7 @@ template const ValueType * any_cast(const any * operand) { + operand->make_unique(); return any_cast(const_cast(operand)); } @@ -219,6 +249,7 @@ template inline ValueType * unsafe_any_cast(any * operand) { + operand->make_unique(); return &static_cast *>(operand->content)->held; }