【问题标题】:Boost::Bind noncopyable error with shared_ptr <tcp::socket>Boost::Bind 不可复制错误与 shared_ptr <tcp::socket>
【发布时间】:2011-11-17 19:28:33
【问题描述】:

我正在尝试以下方法:

boost::shared_ptr< tcp::socket > socket(new tcp::socket( *io_service));

boost::bind(&function, *socket); // compiler error: noncopyable error
function(*socket); // this works fine

void
function(tcp::socket & socket)
{
   //do work
}

为什么我在使用 boost::bind 时会出错?

我后来尝试了以下方法:

boost::shared_ptr< tcp::socket > socket(new tcp::socket( *io_service));
boost::bind(&function, socket); //this works fine now
void function(boost::shared_ptr< tcp::socket > socket)
{
   asio::read_until(&socket, buffer, "end"); // compiler error: says i am passing an invalid argument
}

为什么现在这不起作用?

我知道我缺乏 C/C++ 编程的基本知识。

如果有人可以提供有助于解决此类问题的链接,那就太好了。

【问题讨论】:

    标签: c++ boost boost-asio shared-ptr boost-bind


    【解决方案1】:

    您正在尝试复制不可复制的对象。将其包装在 boost::ref 对象中以将其作为参考:

    boost::bind(&function, boost::ref(*socket));
    

    【讨论】:

      【解决方案2】:

      tcp::socket 不可复制,需要作为参考传递:

      boost::bind(&function, boost::ref(*socket)); 
      

      您可能应该坚持使用您的第二个版本,因为您不必担心套接字对象的生命周期。

      boost::bind(&function, socket); 
      void function(boost::shared_ptr< tcp::socket > socket)
      {
         asio::read_until(*socket, buffer, "end");
      }
      

      【讨论】:

      • 第二种方法的问题是我无法读取套接字,因为它现在是一个指针。我以为我使用了 &socket_ptr,会给我套接字而不是指针。你知道该怎么做吗?
      • 您使用 get() 来获取指针。但这不是您想要传递的,您想要传递对套接字的引用。请参阅我编辑的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多