无法从'const boost :: asio :: const_buffers_1'转换为'boost :: asio :: mutable_buffer'

时间:2011-05-22 12:14:54

标签: c++ boost boost-asio

bool Connection::Receive(){
    boost::shared_ptr<std::string> buffer(new std::string());

    socket_.async_receive(boost::asio::buffer(*buffer), boost::bind(&Connection::handler, this, 
        boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

    //std::cout<<buffer<<std::endl;

    int recvlen = buffer->length();
    if (recvlen <= 0) {
        return false;
    }
    //this->OnReceived(buffer, recvlen);
    return true;
}

错误:

Error   1   error C2440: '<function-style-cast>' : cannot convert from 'const boost::asio::const_buffers_1' to 'boost::asio::mutable_buffer'    e:\boost_1_46_1\boost_1_46_1\boost\asio\detail\buffer_sequence_adapter.hpp  211

1 个答案:

答案 0 :(得分:3)

async_receive函数需要更改缓冲区的内容,但不能更改常量缓冲区。

使用mutable_buffer代替常量缓冲区。您可以找到一些信息here

您需要将指针和大小传递给可变缓冲区:

std::vector<char> content_buffer(max_buffer_size);

... boost::asio::mutable_buffer(content.data(), content.size()) ...

在全局范围内声明content_buffer非常重要,因为async_receive函数正在访问缓冲区异步。如果在函数中声明缓冲区,则在收到数据之前它会超出范围。