这是我尝试编写的一个小函数,用于跟踪我在函数中使用的动态分配(厌倦了一直写 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>'
不知道是什么意思。感谢您的见解:)
最佳答案
首先,您通过了 vector<T*> list
按值,这意味着它被复制并且你的全局 list
保持不变。
这样做:
template <class T>
T* snew(int size, vector<T*>& list)
关于编译问题,打错了,你申请的是*
一次太多了,把用法改成
float* myfloat1 = snew<float>(HEIGHT*WIDTH,list);
sdelete<float>(list);
或者你甚至可以依靠编译器的类型推断而只写
float* myfloat1 = snew(HEIGHT*WIDTH,list);
sdelete(list);
但是这个想法作为一个整体是非常糟糕的,因为如果你有一个 vector
已经,你不想做 new/delete
用手。只需创建一个 vector<float> x(HEIGHT*WIDTH);
并使用它,它会自动删除。
关于c++ - 将 vector 传递给模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6874793/