【发布时间】:2011-07-29 14:37:20
【问题描述】:
这是我正在尝试编写的一个小函数,用于跟踪我在函数中使用的动态分配(厌倦了一直写 delete [])。
template <class T>
T* snew(int size, vector<T*> list)
{
T* pointer = new T[size];
list.push_back(pointer);
return pointer;
}
vector<float*> list;
float* myfloat1 = snew<float*>(HEIGHT*WIDTH,list);
float* myfloat2 = snew<float*>(HEIGHT*WIDTH,list);
float* myfloat3 = snew<float*>(HEIGHT*WIDTH,list);
那么当我需要清除我可以使用的内存时:
template <class T>
void sdelete(vector<T*> list)
{
vector<T*>::iterator it;
for (it = list.begin(); it != list.end(); ++it){
delete [] *it
*it = NULL
}
}
像这样:
sdelete<float*>(list);
当我尝试编译时,我得到:
cannot convert parameter 2 from 'std::vector<_Ty>' to 'std::vector<_Ty,_Ax>'
不知道是什么意思。感谢您的洞察力:)
【问题讨论】:
-
如果你想要一个多维数组,请使用向量的向量或 Boost.MultiArray。
-
您是否考虑过为此使用智能指针或仅使用标准库容器之一?您不需要在应用程序代码中到处写
delete;如果您这样做,则很可能您的代码不正确并且不是异常安全的。 -
正如@James 提到的,智能指针可能是您所需要的。
boost::shared_array是一个不错的例子。 -
@Sander,为什么
vector<float>(WIDTH*HEIGHT)不是一个好的容器? -
为什么不用向量来存储数据?而不是一个向量来跟踪数据?奇数。