gpt4 book ai didi

c++ - 用于异步 boost.asio 操作时 std::string 的生命周期管理

转载 作者:行者123 更新时间:2023-11-28 03:14:30 34 4
gpt4 key购买 nike

通常我使用this使用共享指针管理在 boost.asio 异步操作中使用的缓冲区生命周期的技术。

如果我的缓冲区是一个 std::string 对象(我猜它有点特殊,因为它做了一些内部引用计数)怎么办?我是否仍然需要传递给异步操作处理程序的字符串对象的共享指针?或者以下是否安全? (为什么/为什么不呢?)

void handler()
{
}

void func()
{
std::ostringstream stringbuilder;
// fill stringbuilder

socket.async_send(boost::asio::buffer(stringbuilder.str()), boost:bind(handler));
}

最佳答案

即使 std::string 可能是内部引用计数的,由 std::string 管理的底层内存必须在整个异步操作期间保持有效。它最早可以被销毁是在处理程序的开始。通常,shared_ptr 用于延长缓冲区的生命周期,使其在整个异步操作期间保持有效。

根据 documentation :

One or more buffers containing the data to be written. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

在这种特殊情况下,boost::asio::buffer()通过引用获取字符串。因此,不会发生任何内部引用计数。

template<
typename Elem,
typename Traits,
typename Allocator>
const_buffers_1 buffer(
const std::basic_string< Elem, Traits, Allocator > & data);

一旦 socket.async_send(...) 语句返回,临时 std::stringstringbuilder.str() 返回被销毁,并使异步操作缓冲区的生命周期要求无效。

关于c++ - 用于异步 boost.asio 操作时 std::string 的生命周期管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17361801/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com