c++ - 如何正确使用 boost::make_shared_ptr?

标签 c++ visual-studio-2008 visual-c++ boost boost-asio

这个简单的例子无法在 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/

相关文章:

visual-studio-2008 - Visual Studio 在从 Clearcase 获取版本树时崩溃

c++ - 字符集 - 不清楚

c++ - 最大外部符号长度

visual-studio-2008 - SSRS 错误 : The Report preview failed because the report could not be built

c - GTK : wait for user input

visual-studio-2010 - 在 VS2010 中,VC++ 错误 LNK 2019 with CoolProp 5.0.0

C++:使用指向 unordered_map 的指针或只是将其定义为类中此类型的成员变量?

c++ - SQLite增量整数主键和唯一约束冲突

c++ - 将文件放在 Microsoft Visual Studio 中的什么位置以便自动找到它们?

c# - 重新编译所有依赖项