强制boost :: asio :: buffer通过值复制 [英] Force boost::asio::buffer to copy by value

查看:344
本文介绍了强制boost :: asio :: buffer通过值复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用boost :: asio :: buffer发送消息使用

I use boost::asio::buffer to send a message using

void Send(const std::string& messageData)
{
    socket.async_write(boost::asio::buffer(messageData), ...);
}

在io_service线程中遇到字符串迭代器不可解析运行时错误。当我创建对象的变量来存储缓冲区的消息数据时:

And encounter "string iterator not dereferencable" runtime error somewhere within io_service' thread. When I create objects' variable to store message data for the buffer:

void Send(const std::string& messageData)
{
    this->tempStorage = messageData;
    socket.async_write(boost::asio::buffer(this->tempStorage), ...);
}

错误不会发生。
std :: string(被引用到的messageData)几乎在Send()调用后释放 - boost :: asio :: buffer只存储对对象的引用吗?
如果是,如何强制它按值存储数据?

the error is never occured. std::string (to which messageData is referenced to) is freed almost right after Send() calling - does boost::asio::buffer stores just a reference to object? If so, how can I force it to store the data by value?

推荐答案

列表:

如果是这样,那么它将是完全无用的,因为您没有访问完成处理程序中的任何缓冲区

If it did, it would be completely useless as you do not have access to any of the buffers in your completion handler.

使用buffer()的方法是传递对
存储的引用,以保证一些其他方式的生命周期。

The way to use buffer() is to pass in references to storage that you guarantee the lifetime of in some other way.

你可以将它存储在外部对象中,或者像你一样将它存储在
`this'中,或者将它绑定到完成处理函数
对象本身。

You can either have it stored in an external object, or store it in `this' as you did, or by binding it into the completion handler function object itself.

void onComplete(shared_ptr<std::string> s, error_code const&, size_t)
{
    // do stuff
}

void send(std::string const& messageData)
{
    shared_ptr<std::string> s = make_shared<std::string>(messageData);
    async_send(socket, boost::asio::buffer(*s),
    boost::bind(&T::onSend, this, s, _1, _2));
}

这可以确保缓冲区数据的生命周期至少与
完成处理程序存在。

This ensures that the lifetime of the buffer data is at least as long as the completion handler exists.

这篇关于强制boost :: asio :: buffer通过值复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆