Hi everyone,
The following code gives compiler warnings for the destructor:
Code:
// myVector.h
// forward declarations
template<typename T>
class Iterator; // line 17
template<typename T>
class Vector
{
private:
size_t nb_elms;
T* elms;
Iterator<T>* CreateIterator( void) const
{
return ( new Iterator<T>( *this));
}
public:
Vector( void) : nb_elms( size_t()) {}
~Vector( void) { delete iter; } // line 68
explicit Vector( size_t const& nbelms)
: nb_elms( nbelms), elms( new T[ nb_elms]), iter( CreateIterator())
{}
// iterator
friend class Iterator;
Iterator<T>* iter;
};
Code:
// myVectorIterator.h
// forward class template declaration
template<typename T>
class Vector<T>;
template<typename T>
class Iterator
{
public:
Iterator( const Vector<T>& p_vec) :
vector( &p_vec), index( size_t()){}
Iterator<T>& first( void)
{
index = 0;
return *this;
}
Iterator<T>& next( void)
{
index++;
return *this;
}
T get( void)
{
return vector[index];
}
private:
Vector<T>* vector;
size_t index;
};
here are the warnings:
../Vector.h: In destructor ‘Vector<T>::~Vector() [with T = double]’:
testVector.C:21: instantiated from here
../Vector.h:68: warning: possible problem detected in invocation of delete operator:
../Vector.h:68: warning: invalid use of incomplete type ‘struct Iterator<double>’
../Vector.h:17: warning: declaration of ‘struct Iterator<double>’
../Vector.h:68: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined.
The problem clearly is in the destructor, but when instantiating an object, I create a 'new' iterator in the constructor. So I should provide a destructor which deletes this pointer?
Comments on my iterator pattern are also more than welcome!
EDIT: I am using g++4.3