c – 我可以从它包含的数据中分离std :: vector吗?
发布时间:2020-12-16 04:52:20 所属栏目:百科 来源:网络整理
导读:我正在使用一个函数,它产生一些数据作为std :: vector char和另一个处理数据并使用const char *,size_t len的函数(想想遗留API).有没有办法从向量中分离数据,以便在调用处理函数之前向量可能超出范围而不复制向量中包含的数据(这就是我所说的分离意味着). 一
我正在使用一个函数,它产生一些数据作为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 ); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |