Is it possible to detach std :: vector <char> from the data it contains?

I work with a function that gives some data like std::vector<char>another function (think of deprecated APIs) that processes data and accepts const char *, size_t len. Is there a way to separate the data from the vector so that the vector can go out of scope before calling the processing function without copying the data contained in the vector (which I mean by disconnecting).

Some code sketches to illustrate the scenario:

// Generates data
std::vector<char> generateSomeData();

// Legacy API function which consumes data
void processData( const char *buf, size_t len );

void f() {
  char *buf = 0;
  size_t len = 0;
  {
      std::vector<char> data = generateSomeData();
      buf = &data[0];
      len = data.size();
  }

  // How can I ensure that 'buf' points to valid data at this point, so that the following
  // line is okay, without copying the data?
  processData( buf, len );
}
+5
source share
3 answers
void f() { 
  char *buf = 0; 
  size_t len = 0; 
  std::vector<char> mybuffer; // exists if and only if there are buf and len exist
  { 
      std::vector<char> data = generateSomeData(); 
      mybuffer.swap(data);  // swap without copy
      buf = &mybuffer[0]; 
      len = mybuffer.size(); 
  } 

  // How can I ensure that 'buf' points to valid data at this point, so that the following 
  // line is okay, without copying the data? 
  processData( buf, len ); 
} 
+14
source

The simplest solution has not yet been presented:

void f() { 
   std::vector<char> data = generateSomeData(); 

  processData( &data[0], data.size() ); 
} 
+3

, :

char* ptr = NULL;
int len = -1;
{
    vector<char> vec;
    /* ... fill vec with data ... */
    vec.push_back(NULL); // dont forget to null terminate =)
    ptr = &vec.front();
    len = vec.size();
    // here goes...
    memset((void*)&vec, 0, sizeof(vec));
}
// vec is out of scoop, but you can still access it old content via ptr.
char firstVal = ptr[0];
char lastVal = ptr[len-1];
delete [] ptr; // don't forget to free

Voila!

This code is actually pretty safe, since vec destructor will call delete [] 0;, which is a safe operation (unless you got some weird implementation of stl).

-5
source

All Articles