Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I detach a std::vector<char> from the data it contains?

Tags:

c++

stl

vector

I'm working with a function which yields some data as a std::vector<char> and another function (think of legacy APIs) which processes data and takes a const char *, size_t len. Is there any way to detach 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 (that's what I mean to imply with detaching).

Some code sketch 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 );
}
like image 280
Frerich Raabe Avatar asked Feb 03 '23 02:02

Frerich Raabe


1 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 ); 
} 
like image 166
Alexey Malistov Avatar answered Feb 06 '23 14:02

Alexey Malistov