这个简单的例子无法在 VS2K8 中编译:
io_service io2;
shared_ptr<asio::deadline_timer> dt(make_shared<asio::deadline_timer>(io2, posix_time::seconds(20)));
和这个一样:
shared_ptr<asio::deadline_timer> dt = make_shared<asio::deadline_timer>(io2);
错误是:
error C2664: 'boost::asio::basic_deadline_timer::basic_deadline_timer(boost::asio::io_service &,const boost::posix_time::ptime &)' : cannot convert parameter 1 from 'const boost::asio::io_service' to 'boost::asio::io_service &'
最佳答案
问题是 asio::deadline_timer
的构造函数需要对服务的非常量引用。但是,当您使用 make_shared
时,它的参数是 const
。即make_shared
这部分是问题所在:
template< class T, class A1 > // service is passed by const-reference
boost::shared_ptr< T > make_shared( A1 const & a1 )
{
// ...
::new( pv ) T( a1 ); // but the constructor requires a non-const reference
// ...
}
您可以使用 ref
将服务包装到 reference_wrapper
中:
#include <boost/ref.hpp>
asio::io_service io1;
shared_ptr<asio::deadline_timer> dt = // pass a "reference"
make_shared<asio::deadline_timer>(boost::ref(io1));
这会获取您的实例,并将其放入一个对象中,该对象可以隐式转换为对您的实例的引用。然后,您基本上传递了一个对象表示对您的实例的非常量引用。
这是有效的,因为 reference_wrapper
确实存储了一个指向您的实例的指针。因此它可以返回取消引用的指针,同时仍然是 const
。
关于c++ - 如何正确使用 boost::make_shared_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2422889/