|
Boost : |
From: johan_ericsson_at_[hidden]
Date: 2001-06-12 14:06:45
I looked over the smart pointers at boost.org, and I was surprised not to
find a pointer defined to give value-semantic behavior to polymorphic types.
I have been using such a pointer for a while now in my code, and I have
found it to great use.
Is there a reason why such a pointer has not been included in the libraries?
Is it too basic? Are there well-known limits, or problems to using such a
wrapper?
Here is the code for the pointer that I am using. (Please excuse the
psuedo-hungarian notation). Its not a full featured class, but it should
demonstrate the essentials.
This could be used with any polymorphic type that has a well defined const
Clone() member function.
template <class T> // T requires a Clone() method
class CPolyPtr
{
public:
CPolyPtr():m_Pointer(NULL){} //default constructor:for serialization
CPolyPtr(const CPolyPtr& ptr) : m_Pointer(NULL) //copy constructor
{
if (ptr.m_Pointer.get())
m_Pointer = auto_ptr<T>(ptr.m_Pointer->Clone());
}
explicit CPolyPtr(const T& t) //conversion constructor
{
m_Pointer = auto_ptr<T>(t.Clone());
}
const CPolyPtr& operator=(const CPolyPtr& ptr)
{
CPolyPtr newPtr(ptr); //invoke copy constructor
m_Pointer = newPtr.m_Pointer;
return *this;
//temp copy goes out of scope here
}
const T* operator->() const {return &get();}
T* operator->() {return &get();}
const T& get() const {ASSERT(m_Pointer.get());return *m_Pointer.get();}
//accessor
T& get() {ASSERT(m_Pointer.get());return *m_Pointer.get();}
private:
auto_ptr<T> m_Pointer;
};
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk