I have created a smart pointer class like:
template <class T>
class Owner
{
T* m_p;
public:
Owner(T *p=0) : m_p(p) {}
~Owner() { if (m_p) delete m_p; }
T* operator ->() { return m_p; }
T& operator *() { return *m_p; }
// other members.
};
It works well (resembles to the auto_ptr
in boost library), but now I have the requirements that I want to store an dynamic array of smart pointers in an obj, and it must support:
1) insert new smart pointer into the smart pointers array to let the array resize and acquire the ownership of the new obj,
2) delete one smart pointer on the fly and the resource get freed,
3) when finalizing the array, all objects get deleted.
I was thinking using std::vector<Owner<T> >
, but seems c++ best practice suggests not storing smart pointers in std containers, because copy/assignment behaviors, so what other things can I employ to implement this? something like the OwnerArr in the below example:
class Adapter;
class Computer
{
public:
Computer() {}
~Computer() { // adapters get freed automatically here. }
void insertAdapter(Adapter* pAdapter) { m_adapters->appendOne(pAdapter); }
OwnerArr<Adapter> m_adapters;
};
Thanks in advance!