lo*****@gmail.com wrote:
i want to create a vector of pointer s.t. it can handle new and delete
but also have std::vector interface
can i implement by partial specialization and inherence like follow ?
#include <vector>
#include <algorithm>
template <typename T>
struct delete_ptr {
void operator() (T * p) {
delete p;
}
};
template<typename T>
class auto_vector<T *: public std::vector<T *{
public:
typedef std::vector<T *Base;
~auto_vector() {
clear();
}
void clear() {
std::for_each(begin(), end(), delete_ptr<T>());
Base::clear();
}
void push_back(const T *p) {
T* tmp = new T(*p)
Base::push_back(tmp);
}
};
The stl containers are not designed to be inherited from ( no virtual
destructors ).
Besides, the container you are trying to code is_not a std::vector, it
looks like a std::vector.
What if someone copies that container?
What if the template parameter is a pointer?
I'ld suggest smart pointers as a better alternative to raw allocations.
#include <iostream>
#include <ostream>
#include <vector>
#include <boost/shared_ptr.hpp>
template< typename T >
class auto_vector
{
typedef boost::shared_ptr< T SharedPtrT;
std::vector< SharedPtrT m_vp;
typedef typename std::vector< SharedPtrT >::const_iterator VCIter;
public:
/* ctors */
auto_vector() : m_vp() { }
auto_vector(const auto_vector& r_copy)
{
for(VCIter viter = r_copy.m_vp.begin();
viter != r_copy.m_vp.end(); ++viter)
{
m_vp.push_back( SharedPtrT( new T(*(*viter)) ) );
}
}
/* member functions */
void push_back( const T& t )
{
m_vp.push_back( SharedPtrT( new T(t) ) );
}
void clear()
{
m_vp.clear();
}
/* friends */
friend
std::ostream&
operator<<( std::ostream& os, const auto_vector& r_av )
{
for(VCIter viter = r_av.m_vp.begin();
viter != r_av.m_vp.end(); ++viter)
{
os << *(*viter) << "\n";
}
return os;
}
};
int main()
{
auto_vector< int avn;
for( int i = 0; i < 2; ++i)
{
avn.push_back( i );
}
std::cout << avn << std::endl;
return 0;
}
and the ouput using a simple struct instead of int:
N(int) // temp
N(const N& copy) // push_back
~N() // temp
N(int) // temp
N(const N& copy) // push_back
~N() // temp
0
1
~N()
~N()