Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a vector to a template function

Here is a small function I'm trying to write to keep track of the dynamic allocations I use in my functions (tired of writing delete [] all the time).

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);

So then when I need to clear the memory I can use:

template <class T>
void sdelete(vector<T*> list)
{
    vector<T*>::iterator it;
    for (it = list.begin(); it != list.end(); ++it){
        delete [] *it
        *it = NULL
    }
}

like this:

sdelete<float*>(list);

When I try to compile I get:

cannot convert parameter 2 from 'std::vector<_Ty>' to 'std::vector<_Ty,_Ax>'

Not sure what it means. Thanks for the insight :)

like image 353
Smash Avatar asked Apr 10 '26 07:04

Smash


1 Answers

First and foremost, you pass vector<T*> list by value, which means that it gets copied and your global list is left unchanged.

Do it like this:

template <class T>
T* snew(int size, vector<T*>& list)

As for the compilation issue, there's a typo, you're applying * one time too much, change the usages to

float* myfloat1 = snew<float>(HEIGHT*WIDTH,list);
sdelete<float>(list);

Or you could even rely on compiler's type inference and just write

float* myfloat1 = snew(HEIGHT*WIDTH,list);
sdelete(list);

But the idea as a whole is pretty much a bad one, because if you have a vector already, you don't want to do new/delete by hand. Just create a vector<float> x(HEIGHT*WIDTH); and use it, it gets removed automatically.

like image 165
unkulunkulu Avatar answered Apr 11 '26 20:04

unkulunkulu