Prevent data release when the vector goes beyond

Is there a way to transfer ownership of the data contained in std :: vector (denoted by, say, T * data) to another construction, preventing the "data" from becoming a sagging pointer after the vector goes beyond the bounds?

EDIT: I DO NOT WANT TO COPY DATA (which would be a simple but ineffective solution).

In particular, I would 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 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 C interface
}

The only thing that comes to mind to imitate this is:

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

and then the data will either be freed or (in my case) to be used as mxSetData (mxArrayA, doubleledata). However, this leads to a small memory leak (data structure for processing v capacity, size, etc., but not the data itself, of course).

Is a leak possible?

+5
5

:

vector<double> myown;

vector<double> someoneelses = foo();

std::swap( myown, someoneelses );

, , , - , . , .

+5

std::vector :

  • ;
  • const-ref ( );
  • , &v[0].

, - , std::vector , , . std::copy().

+5

, ( , std:: copy, std:: swap ..). - ( ),

+1

- ?

int main()
{
    double *data = 0;
    {
        vector<double> foo;
        // insert some elements to foo

        data = new double[foo.size()];
        std::copy(foo.begin(), foo.end(), &data[0]);
    }

    // Pass data to Matlab function.
    delete [] data;
    return 0;
}
0

, , .

void f()
{
    std::vector<boost::shared_ptr<double> > doubles;
    InitVector(doubles);

    std::vector<boost::shared_ptr<double> > newDoubles(doubles);
}

You really cannot transfer ownership of data between standard containers without making copies of them, since standard containers always copy the data that they encapsulate. If you want to minimize the overhead of copying expensive objects, then it's a good idea to use a smart pointer with reference counting to wrap your expensive data structure. boost::shared_ptrsuitable for this task, since it is pretty cheap to make a copy of it.

-2
source

All Articles