Boost.asio和异步链,unique_ptr? [英] Boost.asio and asynchronous chain, unique_ptr?

查看:97
本文介绍了Boost.asio和异步链,unique_ptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对异步编程并不很熟悉,我有一个问题.

I am not deeply familiar with async programming and I have a question.

我的问题如下.给定boost.asio中C ++ 11的echo_server示例:

My question is the following. Given the echo_server example here for C++11 in boost.asio: http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/example/cpp11/spawn/echo_server.cpp

我想知道是否可以在C ++ 14中将std::make_shared<session>替换为C ++ 14中的std::unique_ptr<session>,从而避免引用计数的开销.

I would like to know if the std::make_shared<session> can be replaced in C++14 with a std::unique_ptr<session>in C++14, avoiding the overhead of reference count.

我不确定,因为我们有shared_from_this(),但没有类似unique_from_this()的东西,那么如何从this内部访问unique_ptr<session>?

I am not sure since we have shared_from_this() but not something like unique_from_this(), so how can I access the unique_ptr<session> from inside this?.

推荐答案

不,在asio编程中使用shared_ptr是惯用的.

No, the use of shared_ptr in asio programming is idiomatic.

这个想法是,未完成处理程序的数量与启动异步操作的对象的共享计数匹配.这是通过将shared_ptr管理对象的副本绑定到处理程序函数对象中来实现的.

The idea is that the number of outstanding handlers is matched by the shared-count of the object initiating the async operations. This is achieved by binding a copy of the shared_ptr managing the object into the handler function objects.

c ++ 11/14的方式是将boost::shared_ptr替换为std::shared_ptr(std::bind,lambdas等也可以与asio完美配合).

The c++11/14 way would be to replace the boost::shared_ptr with std::shared_ptr (std::bind, lambdas, etc also work perfectly well with asio).

更新,现在我已经完全理解了这个问题:

Update, now that I fully understand the question:

在您链接的示例中,我认为您是指在go()方法中创建的名为self的shared_ptr吗?如果需要,可以不使用shared_ptr来编写它.您必须将其删除作为go()的最后一行.您还必须记住捕获任何异常,以确保采用了此代码路径.当然可以设置一个unique_ptr来执行此操作,但是在会话的构造与成功创建采用unique_ptr之间,您会遇到一个生命周期管理问题. shared_ptr减轻了一个原子公司成本的管理负担.

In the example you linked, I take it that you're referring to the shared_ptr called self which is created in the method go() ? You could write it without the shared_ptr if you wanted. You'd have to put a delete this as the last line of go(). You'd also have to remember to catch any exceptions to ensure this code path was taken. A unique_ptr could be set up to do this of course, but then you've got a lifetime management issue between the construction of the session and the successful creation of the adopting unique_ptr. shared_ptr eases the management burden for the cost of one atomic inc...

在这种情况下,答案严格是是",但是我建议恕我直言,因为它比较脆弱.

In which case the answer is strictly "yes", but imho I'll-advised as it's more brittle.

这篇关于Boost.asio和异步链,unique_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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