From: Martin Ling Date: Tue, 2 Sep 2014 18:21:11 +0000 (+0100) Subject: C++: Fix duplicated shared_ptr creation. X-Git-Tag: libsigrok-0.4.0~1052 X-Git-Url: https://sigrok.org/gitaction?a=commitdiff_plain;h=0d0170ae9e4743e3918a3c9709c026f93d714a4f;p=libsigrok.git C++: Fix duplicated shared_ptr creation. --- diff --git a/bindings/cxx/include/libsigrok/libsigrok.hpp b/bindings/cxx/include/libsigrok/libsigrok.hpp index 35b3d441..ca9c119b 100644 --- a/bindings/cxx/include/libsigrok/libsigrok.hpp +++ b/bindings/cxx/include/libsigrok/libsigrok.hpp @@ -125,8 +125,7 @@ public: }; /* Base template for most classes which wrap a struct type from libsigrok. */ -template class SR_API StructureWrapper : - public enable_shared_from_this > +template class SR_API StructureWrapper { protected: /* Parent object which owns this child object's underlying structure. @@ -144,24 +143,41 @@ protected: references to both the parent and all its children are gone. */ shared_ptr parent; + /* Weak pointer for shared_from_this() implementation. */ + weak_ptr > weak_this; + public: + /* Note, this implementation will create a new smart_ptr if none exists. */ + shared_ptr > shared_from_this() + { + shared_ptr > shared; + + if (!(shared = weak_this.lock())) + { + shared = shared_ptr >( + this, reset_parent); + weak_this = shared; + } + + return shared; + } + shared_ptr > - get_shared_pointer(Parent *parent) + get_shared_pointer(shared_ptr parent) { if (!parent) throw Error(SR_ERR_BUG); - this->parent = static_pointer_cast(parent->shared_from_this()); - return shared_ptr >( - this, reset_parent); + this->parent = parent; + return shared_from_this(); } + shared_ptr > - get_shared_pointer(shared_ptr parent) + get_shared_pointer(Parent *parent) { if (!parent) throw Error(SR_ERR_BUG); - this->parent = parent; - return shared_ptr >( - this, reset_parent); + return get_shared_pointer(static_pointer_cast( + parent->shared_from_this())); } protected: static void reset_parent(StructureWrapper *object)