c++ - 通用容器清除过程中的异常,C++

标签 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] 我只能删除 &*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;
}

感谢您的帮助...

最佳答案

delete &*i_items; 应该是 delete *i_items;。你不是要删除指针的地址,你是要删除指针!我没有看到以下行 (*i_items) = 0 的原因;//异常)。

最后,为什么要用指针插入点呢?只需插入实际点并改用 std::vector 即可。如果您想要自动删除其内容的容器,请考虑 boost pointer containers .

关于c++ - 通用容器清除过程中的异常,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4770446/

相关文章:

html - 为网站的不同页面制作 CSS 样式表

html - 购买的 joomla 模板在 flash 内容后没有文字

对 C 中的指针和泛型(void)指针感到困惑

c++ - 在c++中生成随机数

c++ - 我是否需要删除我创建的 boost 线程?

c++ - 如何使用 std::sqrt 作为 std::function?

c++ - 请求转换为非标量类型

java - 使用泛型类型动态计算 float 和整数

c++ - 从 C++ 执行命令,argv[0] 中预期的是什么?

c++ - 何时使用 Eigen::Vector 与 std::vector?