[英]Passing a unique_ptr reference to boost::bind?
I'm on CentOS 6.6 (gcc 4.4.7) and developing with Boost.Asio (1.41). 我使用的是CentOS 6.6(gcc 4.4.7)并使用Boost.Asio(1.41)进行开发。 I'd like io_service to call member function run()
in manger object m
when it starts. 我希望io_service在manger对象m
启动时调用成员函数run()
。 The code I'm trying to compile looks like: 我正在尝试编译的代码如下:
#include <memory>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
boost::asio::io_service io;
std::unique_ptr<manager> m;
m = std::make_unique<manager>;
io.post(boost::bind(&manager::run, &m));
gcc pitches a fit on the boost::bind
statement, which includes: gcc适用于boost::bind
语句,其中包括:
/usr/include/boost/bind/mem_fn_template.hpp:40: error: pointer to
member type ‘void (manager::)()’ incompatible with object type
‘std::unique_ptr<manager, std::default_delete<manager> >’
What do I want to be doing here? 我想在这做什么?
The manager object will only know about timers; 经理对象只会知道计时器; a separate object that knows about io_service will get added to its constructor later. 知道io_service的单独对象将在以后添加到其构造函数中。 But the idea is that manager::run()
will create an initial set of timers to bootstrap the system. 但是想法是manager::run()
将创建一组初始定时器来引导系统。
Clarification: 澄清:
My thinking here is that the outer block of code manages the lifetime of m
and that the next statement will be io.run()
. 我的想法是外部代码块管理m
的生命周期,下一个语句将是io.run()
。 The outer code will destroy m
when io.run()
returns. 当io.run()
返回时,外部代码将销毁m
。 Hence, passing a raw reference for m
to io
is appropriate. 因此,将m
的原始引用传递给io
是合适的。 But I'm a modern C++ novice and could be way off base here. 但我是一个现代的C ++新手,可能会离开这里。
You'd need C++-14 and generalized lambda capture to make this work -- you'd need to move the unique pointer into the lambda. 你需要C ++ - 14和广义lambda捕获才能使它工作 - 你需要将唯一指针移动到lambda中。 Instead, just use a shared_ptr
, which std::bind
understands natively: 相反,只需使用一个shared_ptr
, std::bind
本身可以理解:
std::shared_ptr<manager> m;
m = std::make_shared<manager>();
io.post(std::bind(&manager::run, std::move(m)));
The std::move
is optional but ensures that m
doesn't keep the manager around when it's not wanted. std::move
是可选的,但确保m
不会在不需要时保持经理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.