I'm far from being able to tell what you should do here (missing information and only used asio a couple of times), but guessing from this example, you should be able to pass your buffer using a custom buffer class similar to:
// based on http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/example/cpp11/buffers/reference_counted.cpp
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
template<class T>
class shared_const_buffer
{
public:
// Construct from a `shared_ptr`
explicit shared_const_buffer(std::shared_ptr<std::vector<T>> const& p_data)
: data_(p_data),
buffer_(boost::asio::buffer(*data_))
{}
// Implement the ConstBufferSequence requirements.
using value_type = boost::asio::const_buffer;
using const_iterator = boost::asio::const_buffer const*;
boost::asio::const_buffer const* begin() const { return &buffer_; }
boost::asio::const_buffer const* end() const { return &buffer_ + 1; }
private:
std::shared_ptr<std::vector<T>> data_;
boost::asio::const_buffer buffer_;
};
As mentioned in my comments to the question, I do not know if passing around shared buffers for sending (writing) is a good idea.
How this works:
In the write function, you pass in a buffer:
boost::asio::async_write( socket_,
boost::asio::buffer(backupVector), /*...*/ );
In this example, the buffer is created via the boost::asio::buffer
function. But this function doesn't acquire (and doesn't share) ownership of the argument, it solely stores a reference / pointer. The passed buffer object is copied into the socket (in the job queue), where it lives until the job is done.
By using shared_const_buffer
instead of the buffer object created by boost::asio::buffer
, we extend the lifetime of the vector to at least the lifetime of the created shared_const_buffer
object. Therefore, the vector lives at least until the job is done.
See the documentation of async_write
and the documentation of the buffer
function / buffer invalidation.