Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preventing data from being freed when vector goes out of scope

Is there a way to transfer ownership of the data contained in a std::vector (pointed to by, say T*data) into another construct, preventing having "data" become a dangling pointer after the vector goes out of scope?

EDIT: I DON'T WANT TO COPY THE DATA (which would be an easy but ineffective solution).

Specifically, I'd like to have something like:

template<typename T>
    T* transfer_ownership(vector<T>&v){
    T*data=&v[0];
    v.clear();
    ...//<--I'd like to make v's capacity 0 without freeing data 
}

int main(){
    T*data=NULL;
    {
        vector<double>v;
        ...//grow v dynamically
        data=transfer_ownership<double>(v);
    }
    ...//do something useful with data (user responsible  for freeing it later)
   // for example mxSetData(mxArray*A,double*data) from matlab's C interface
}

The only thing that comes to my mind to emulate this is:

{
    vector<double>*v=new vector<double>();
    //grow *v...
    data=(*v)[0];
}

and then data will later either be freed or (in my case) used as mxSetData(mxArrayA,doubledata). However this results in a small memory leak (data struct for handling v's capacity, size, etc... but not the data itself of course).

Is it possible without leaking ?

like image 874
spirov Avatar asked Nov 13 '09 05:11

spirov


2 Answers

A simple workaround would be swapping the vector with one you own:

vector<double> myown;

vector<double> someoneelses = foo();

std::swap( myown, someoneelses );

A tougher but maybe better approach is write your own allocator for the vector, and let it allocate out of a pool you maintain. No personal experience, but it's not too complicated.

like image 130
xtofl Avatar answered Sep 22 '22 18:09

xtofl


The point of using a std::vector is not to have to worry about the data in it:

  • Keep your vector all along your application;
  • Pass it by const-ref to other functions (to avoid unnecessary copies);
  • And feed functions expecting a pointer-to-T with &v[0].

If you really don't want to keep your vector, you will have to copy your data -- you can't transfer ownership because std::vector guarantees it will destroy its content when going out-of-scope. In that case, use the std::copy() algorithm.

like image 26
Julien-L Avatar answered Sep 19 '22 18:09

Julien-L