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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With