通用容器清除期间的异常,C ++

时间:2011-01-22 20:42:06

标签: c++ templates generic-programming

我在清除通用容器时遇到问题。在执行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]我只能删除&amp; * 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;
}

感谢您的帮助......

2 个答案:

答案 0 :(得分:3)

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

最后,为什么要通过指针插入点?只需插入实际点并使用std::vector代替。如果您想要自动delete其内容的容器,请考虑boost pointer containers

答案 1 :(得分:0)

据我所知,

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

GContainer按值存储Point的实例,而不是指向Point的指针。

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