Exception during generic container clearing, C++
I am having problems with clearing of the generic container. In carrying out the function clear() the program fails.
Base class:
//Generic container
template <class Item>
struct TList
{
typedef std::vector <Item> Type;
};
template <class Item>
class GContainer
{
protected:
typename TList <Item>::Type items;
public:
GContainer() : items (0) {}
virtual ~GContainer() = 0;
public:
typename TList <Item>::Type ::iterator begin() { return items.begin(); }
typename TList <Item>::Type ::iterator end() { return items.end(); }
...
};
开发者_开发知识库
Derived class:
//Generic container for points
template <class Point>
class ContPoints : public GContainer <Point>
{
public:
void clear();
...
};
//Specialization
template <class Point>
class ContPoints <Point *> : public GContainer <Point>
{
public:
void clear();
...
};
Implementation of the method clear()
template <class Point>
void ContPoints <Point *>::clear()
{
for ( typename TItemsList <Point>::Type ::iterator i_items = items.begin(); i_items != items.end(); ++i_items )
{
//Delete each node
if ( &(i_items) != NULL )
{
delete * i_items //Compile error, not usable, why ???
delete &*i_items; //Usable, but exception
*i_items) = 0; //Than exception
}
}
items.clear(); //vector clear
}
Suprisingly:
A] I am not able to delete *i_items...
delete *i_items; //Error C2440: 'delete' : cannot convert from 'Point<T>' to 'void *
B] I am able to delete only &*i_items...
int _tmain(int argc, _TCHAR* argv[])
{
ContPoints <Point<double> *> pll;
pll.push_back (new Point <double>(0,0));
pll.push_back (new Point <double>(10,10));
pll.clear(); //Exception
return 0;
}
Thanks for your help...
delete &*i_items;
should be delete *i_items;
. You don't want to delete the address of the pointer, you want to delete the pointer! I don't see a reason for the following line (*i_items) = 0; //Exception
) at all.
Finally, why insert points by pointer? Just insert the actual points and use std::vector
instead. If you want containers which automatically delete
their contents, consider boost pointer containers.
As far as I can see from this
template <class Point>
class ContPoints <Point *> : public GContainer <Point>
the GContainer
is storing instances of Point
by value, not pointers to Point
.
This is confirmed by the error message: cannot convert a Point<T>
to a pointer.
精彩评论