Domanda

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!

È stato utile?

Soluzione

You can't store your Owner, or std::auto_ptr (which you shouldn't use anyway, since it's deprecated), in a standard container because they are not really copyable.

In C++11, there's std::unique_ptr: a single-ownership smart pointer to replace auto_ptr, which is movable but not copyable. This can be moved or emplaced into any container, as long as you don't need to do anything that involves copying it. If you need multiple pointers to share ownership of the same object, then you can use std::shared_ptr instead.

If you're stuck with an older language version for some reason, then Boost can give you smart pointers, including a shared_ptr very similar to the standard one, or pointer containers similar to your OwnerArray.

If you do decide to roll your own resource management classes, always remember the Rule of Three. The classes you show have implicitly generated copy constructors and copy-assignment operators which can cause two pointers to own - and try to delete - the same object, which is very bad. You need to either prevent copying (by deleting these functions, or (pre-2011) declaring them private with no implementation), or implement some kind of safe copy semantics.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top