我正在开发用于库的异步网络代码,我的代码旨在发送'数据非常完美:
//connection_id is a wrapper around a size_t
//data_vector is an alias for std::vector<unsigned char>
bool write_to_connection(const connection_id & id, const data_vector & data) {
if (connections.contains(id)) {
std::shared_ptr<data_vector> write_buffer = std::make_shared<data_vector>(data);
connection_ptr conn = connections[id];
conn->get_socket().async_write_some(
boost::asio::buffer(
*write_buffer
),
std::bind(
&basic_server::write,
this,
std::placeholders::_1,
std::placeholders::_2,
id,
write_buffer
)
);
return true;
}
return false;
}
void write(const boost::system::error_code & ec, size_t bytes_written, const connection_id & id, std::shared_ptr<data_vector> write_buffer) {
if (ec) {
connections.erase(id);
}
}
但是,出于性能原因,我不喜欢使用std::shared_ptr
来维护我的数据,特别是因为我可能会同时发出许多这样的回调。我甚至不在回调函数中使用它,只添加它以确保数据缓冲区的生命周期持续到写入完成。
我想使用std::unique_ptr
,因为我在逻辑上只需要在任何给定时间获得该对象的一个副本,这些副本会被传递(读取:移动)到回调函数,我这样写的:
//connection_id is a wrapper around a size_t
//data_vector is an alias for std::vector<unsigned char>
bool write_to_connection(const connection_id & id, const data_vector & data) {
if (connections.contains(id)) {
std::unique_ptr<data_vector> write_buffer = std::make_unique<data_vector>(data);
connection_ptr conn = connections[id];
conn->get_socket().async_write_some(
boost::asio::buffer(
*write_buffer
),
std::bind(
&basic_server::write,
this,
std::placeholders::_1,
std::placeholders::_2,
id,
std::move(write_buffer) //So that we're not performing a copy; we're performing a move
)
);
return true;
}
return false;
}
void write(const boost::system::error_code & ec, size_t bytes_written, const connection_id & id, std::unique_ptr<data_vector> write_buffer) {
if (ec) {
connections.erase(id);
}
}
然而,这很快就给了我这个(相当详细的)编译错误:
Error C2280 'std::_Binder<std::_Unforced,void (__cdecl server::basic_server::* )(const boost::system::error_code &,size_t,const server::connection_id &,std::unique_ptr<server::data_vector,std::default_delete<_Ty>>),server::basic_server *const ,const std::_Ph<1> &,const std::_Ph<2> &,const server::connection_id &,std::unique_ptr<_Ty,std::default_delete<_Ty>>>::_Binder(const std::_Binder<std::_Unforced,void (__cdecl server::basic_server::* )(const boost::system::error_code &,size_t,const server::connection_id &,std::unique_ptr<_Ty,std::default_delete<_Ty>>),server::basic_server *const ,const std::_Ph<1> &,const std::_Ph<2> &,const server::connection_id &,std::unique_ptr<_Ty,std::default_delete<_Ty>>> &)': attempting to reference a deleted function Send File To Server C:\Users\rengland\Workspace_CPP\Library\Includes\boost\asio\basic_stream_socket.hpp 729
我假设它在抱怨,因为代码认为我试图复制std::unique_ptr
,尽管我打算将其转移到回调函数中。我有什么办法可以解决这个问题,或者我应该让自己辞职以使用std::shared_ptr
版本吗?