Reputation: 1735
I have a function that has the following signature and which I cannot change:
bool function(uint8_t*& data, uint32_t size)
I want to pass a std vector, I am able to do it as follows:
std::vector<uint8_t> buffer;
buffer.reserve(10);
buffer.resize(10);
uint8_t* data = &buffer[0];
function(data, buffer.size()))
Is there a way to avoid creating the data
pointer? The following doesn't compile:
function(&buffer[0], buffer.size()))
gives a no matching function
error.
Upvotes: 5
Views: 1096
Reputation: 50778
You probably need this:
uint8_t* data = buffer.data(); // data will point to the first element of the vector
function(data, buffer.size());
// function may have modified the data pointer at this point
Now I would be interesting what exactly function
does, especially if it does modify data
.
BTW: IMO buffer.reserve(10);
is useless as you have a buffer.resize(10);
right after anyway.
Upvotes: 2
Reputation: 1544
The main problem here is that if function
takes a reference to a pointer, it may modify it which would result in unexpected results.
If you are sure the function doesn't modify the pointer itself, you could add an overload to simplify what you want to accomplish:
bool function(uint8_t*& data, uint32_t size) {
return false;
}
// overloaded on rvalue reference to pointer
bool function(uint8_t*&& data, uint32_t size) {
return function(data, size);
}
int main() {
std::vector<uint8_t> buffer;
buffer.reserve(10);
buffer.resize(10);
function(buffer.data(), buffer.size());
}
Take into account that this is dangerous, especially if function
modifies the pointer, so use with caution.
Upvotes: 3