我正在使用一个函数,它产生一些数据作为std :: vector< char>和另一个处理数据并使用const char *,size_t len的函数(想想遗留API).有没有办法从向量中分离数据,以便在调用处理函数之前向量可能超出范围而不复制向量中包含的数据(这就是我所说的分离意味着).
一些代码草图来说明场景:
// 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 ); }