Reputation: 8239
I am trying to use boost::asio::buffer as a reference parameter in my method like this:
void ReadDataIntoBufferPassedIn(boost::asio::buffer & buffer);
Firstly, compiler complains that:
error: no type named 'buffer' in namespace 'boost::asio' void ReadDataIntoBufferPassedIn(boost::asio::buffer & buffer);
This looks like it requires me to templatise the method here, but my question is a little beyond just fixing the error.
Question:
What is the best way to do this without causing extra copies of the asio::buffer
I pass in? a templatised way? How? If not, how can I resolve this error & still be able to pass in boost::asio::buffer
as a method param?
Upvotes: 2
Views: 1441
Reputation: 76
From your question it is not clear to me if you are aware that the boost::asio::buffer
is a function that creates buffer objects (mutable or const), so this explains the compilation error. Buffer object is just a handle to some contiguous chunk of memory and it contains just a pointer to the raw data and the size of it - a (void*
, size_t
) pair.
If you need to modify the underlying data you can do this by passing a reference to mutable_buffer and fiddling with it as shown in:
http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/reference/mutable_buffer.html but it should be much safer (type-safety-wise) to just pass the actual container for your data instead of the buffer
view of it.
UPDATE: You don't really need to make your function a template as you suggest in the other answer. Also, an rvalue reference may not be needed. It all depends on what you want to do with the function.
void ReadDataIntoBufferPassedIn(const boost::asio::mutable_buffer& buffer) {
int* p = boost::asio::buffer_cast<int*>(buffer);
*p = 5; // Do whatever you want with p
}
std::vector<int> v{1,2,3};
ReadDataIntoBufferPassedIn(boost::asio::buffer(v));
Upvotes: 3
Reputation: 8239
I figured that I need to templatise with universal reference like this be able to pass in a prepared boost::asio::buffer
into my method.
template <class TheBuffer>
void ReadDataIntoBufferPassedIn(TheBuffer && buffer) {
}
Above technique works well invoking the method in this way for example:
std::vector<unsigned char> buf;
ReadDataIntoBufferPassedIn(boost::asio::buffer(buf));
There are other ways also the invocation fits in well.
Upvotes: 0