我可以分离 std::vector<char> 吗?从它包含的数据? [英] Can I detach a std::vector&lt;char&gt; from the data it contains?

查看:27
本文介绍了我可以分离 std::vector<char> 吗?从它包含的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个函数,该函数将一些数据作为 std::vector 和另一个处理数据并采用 const char 的函数(想想遗留 API)*, size_t len.有什么方法可以将数据与向量分离,以便向量可以在调用处理函数之前超出范围复制向量中包含的数据(这就是我用 分离).

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

推荐答案

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

这篇关于我可以分离 std::vector<char> 吗?从它包含的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆