gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:08:41 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com