0

我在清除通用容器时遇到问题。在执行 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;
}

谢谢你的帮助...

4

2 回答 2

3

delete &*i_items;应该是delete *i_items;。你不想删除指针的地址,你想删除指针!我根本看不到下一行 ( *i_items) = 0; //Exception) 的原因。

最后,为什么要通过指针插入点?只需插入实际点并使用std::vector即可。如果您想要自动显示delete其内容的容器,请考虑提升指针容器

于 2011-01-22T20:54:15.557 回答
0

据我所见

template <class Point>
class ContPoints <Point *> : public GContainer <Point>

是按值GContainer存储实例Point,而不是指向Point.

错误消息证实了这一点:无法将 a 转换Point<T>为指针。

于 2011-01-22T21:18:14.453 回答