我在清除通用容器时遇到问题。在执行 clear() 函数时,程序失败。
基类:
//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(); }
...
};
派生类:
//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();
...
};
方法 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
}
令人惊讶的是:
A] 我无法删除 *i_items...
delete *i_items; //Error C2440: 'delete' : cannot convert from 'Point<T>' to 'void *
B] 我只能删除 &*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;
}
谢谢你的帮助...