Allow constructing/assigning wxObjectDataPtr from compatible type

Generalize copy ctor and assignment operators to allow implicit
conversions from wxObjectDataPtr<D> to wxObjectDataPtr<B> if D is
implicitly convertible to B (e.g. if B is the base class and D is a
class derived from it).

This makes wxObjectDataPtr<> more like standard smart pointer classes
and more useful.
This commit is contained in:
Vadim Zeitlin
2020-12-30 01:02:47 +01:00
parent be5f1344b6
commit 04bbb844ae
2 changed files with 30 additions and 0 deletions

View File

@@ -278,6 +278,15 @@ public:
m_ptr->IncRef(); m_ptr->IncRef();
} }
// generalized copy ctor: U must be convertible to T
template <typename U>
wxObjectDataPtr(const wxObjectDataPtr<U> &tocopy)
: m_ptr(tocopy.get())
{
if (m_ptr)
m_ptr->IncRef();
}
~wxObjectDataPtr() ~wxObjectDataPtr()
{ {
if (m_ptr) if (m_ptr)
@@ -330,6 +339,17 @@ public:
return *this; return *this;
} }
template <typename U>
wxObjectDataPtr& operator=(const wxObjectDataPtr<U> &tocopy)
{
if (m_ptr)
m_ptr->DecRef();
m_ptr = tocopy.get();
if (m_ptr)
m_ptr->IncRef();
return *this;
}
wxObjectDataPtr& operator=(T *ptr) wxObjectDataPtr& operator=(T *ptr)
{ {
if (m_ptr) if (m_ptr)

View File

@@ -585,11 +585,17 @@ public:
*/ */
wxObjectDataPtr(T* ptr = NULL); wxObjectDataPtr(T* ptr = NULL);
//@{
/** /**
This copy constructor increases the count of the reference counted object to This copy constructor increases the count of the reference counted object to
which @a tocopy points and then this class will point to, as well. which @a tocopy points and then this class will point to, as well.
Using @a U different from @c T is only supported since wxWidgets 3.1.5.
*/ */
template <typename U>
wxObjectDataPtr(const wxObjectDataPtr<U>& tocopy);
wxObjectDataPtr(const wxObjectDataPtr<T>& tocopy); wxObjectDataPtr(const wxObjectDataPtr<T>& tocopy);
//@}
/** /**
@@ -649,7 +655,11 @@ public:
//@{ //@{
/** /**
Assignment operator. Assignment operator.
Using @a U different from @c T is only supported since wxWidgets 3.1.5.
*/ */
template <typename U>
wxObjectDataPtr<T>& operator=(const wxObjectDataPtr<U>& tocopy);
wxObjectDataPtr<T>& operator=(const wxObjectDataPtr<T>& tocopy); wxObjectDataPtr<T>& operator=(const wxObjectDataPtr<T>& tocopy);
wxObjectDataPtr<T>& operator=(T* ptr); wxObjectDataPtr<T>& operator=(T* ptr);
//@} //@}