C++ boost库----share_from_this类的作用和实现原理

使用Boost共享对象
本文解析了在使用Boost库时,如何正确地利用enable_share_from_this实现类实例的共享指针管理,尤其关注在异步操作中传递当前对象自身的问题。

使用boost库时,经常会看到如下的类

class A:public enable_share_from_this<A>

在什么情况下要使类A继承enable_share_from_this?

使用场合:当前类A的实例对象正被share_ptr管理,且在类A的成员函数里需要把当前类对象作为参数传给其他函数时,就需要传递一个指向此类A的实例对象自身的share_ptr。

我们就使类A继承enable_share_from_this,然后通过其成员函数share_from_this()返回当指向自身的share_ptr。


以上有2个疑惑:

1.把当前类对象作为参数传给其他函数时,为什么要传递share_ptr呢?直接传递this指针不可以吗?

一个裸指针传递给调用者,谁也不知道调用者会干什么?假如调用者delete了该对象,而share_tr此时还指向该对象。

2.这样传递share_ptr可以吗?share_ptr<this>

这样会造成2个非共享的share_ptr指向一个对象,最后造成2次析构该对象。


boost官方文档中一个非常典型的例子:http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/tutorial/tutdaytime3/src.html

部分代码:

复制代码
 1 class tcp_connection
 2   : public boost::enable_shared_from_this<tcp_connection>
 3 {
 4 public:
 5   typedef boost::shared_ptr<tcp_connection> pointer;
 6 
 7   static pointer create(boost::asio::io_service& io_service)
 8   {
 9     return pointer(new tcp_connection(io_service));
10   }
11 
12   tcp::socket& socket()
13   {
14     return socket_;
15   }
16 
17   void start()
18   {
19     message_ = make_daytime_string();
20 
21     boost::asio::async_write(socket_, boost::asio::buffer(message_),
22         boost::bind(&tcp_connection::handle_write, shared_from_this(),
23           boost::asio::placeholders::error,
24           boost::asio::placeholders::bytes_transferred));
25   }
26 
27 private:
28   tcp_connection(boost::asio::io_service& io_service)
29     : socket_(io_service)
30   {
31   }
32 
33   void handle_write(const boost::system::error_code& /*error*/,
34       size_t /*bytes_transferred*/)
35   {
36   }
37 
38   tcp::socket socket_;
39   std::string message_;
40 };
复制代码

类tcp_connection继承enable_share_from_this,在22行里,它的成员函数start(),通过share_from_this返回指向自身的share_ptr。

实现原理:

share_from_this()是如何返回指向该对象的share_ptr的?显然它不能直接return share_ptr<this>。因为它返回的share_ptr必须和管理该对象的share_ptr是共享的,也就是说返回的share_ptr的引用计数和管理该对象的share_ptr的引用计数是相同的。其实enable_share_from_this就存储了管理该对象的share_ptr的引用计数,通过weak_ptr来实现。在enable_share_from_this,里有一个成员weak_this_。

但现在的问题是:何时初始化这个 weak_ptr ?因为类对象生成时还没有生成相应的用来管理这个对象的 shared_ptr 。其实是通过share_ptr的构造函数中初始化这个weak_ptr的.

shared_ptr 定义了如下构造函数:
1  template<class Y>
2 explicit shared_ptr( Y * p ): px( p ), pn() // Y must be complete
3 {
4   boost::detail::sp_pointer_construct( this, p, pn );
5 }
里面调用了  boost::detail::sp_pointer_construct 
复制代码
1 template< class T, class Y > inline void sp_pointer_construct( boost::shared_ptr< T > * ppx, Y * p, boost::detail::shared_count & pn )
2 {
3    boost::detail::shared_count( p ).swap( pn );
4    boost::detail::sp_enable_shared_from_this( ppx, p, p );
5 }
复制代码
 里面又调用了boost::detail::sp_enable_shared_from_this
 
share_ptr有2个该重载函数
复制代码
1 template< class X, class Y, class T > inline void sp_enable_shared_from_this( boost::shared_ptr<X> const * ppx, Y const * py, boost::enable_shared_from_this< T > const * pe )
2 {
3   if( pe != 0 )
4  {
5    pe->_internal_accept_owner( ppx, const_cast< Y* >( py ) );
6  }
7 }
复制代码
1 inline void sp_enable_shared_from_this( ... )
2 {
3 }

由于我们的类是继承enable_share_from_this,所以调用的是前者

里面又调用了 enable_shared_from_this 的 _internal_accept_owner :
复制代码
template<class X, class Y> void _internal_accept_owner( shared_ptr<X> const * ppx, Y * py ) const
{
  if( weak_this_.expired() )
  {
    weak_this_ = shared_ptr<T>( *ppx, py );
  }
}
复制代码

最后,在这里对enable_shared_from_this 的成员 weak_this_ 进行拷贝赋值,使得整个 weak_ptr 作为类对象shared_ptr 的一个观察者。当调用share_from_this()时,就可以从这个 weak_ptr 来生成了,且引用计数是相同的。

复制代码
1 shared_ptr<T const> shared_from_this() const
2 {
3  shared_ptr<T const> p( weak_this_ );
4  BOOST_ASSERT( p.get() == this );
5  return p;
6 }
复制代码
- The C compiler identification is GNU 11.4.0 -- The CXX compiler identification is GNU 11.4.0 -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Check for working C compiler: /usr/bin/cc - skipped -- Detecting C compile features -- Detecting C compile features - done -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Check for working CXX compiler: /usr/bin/c++ - skipped -- Detecting CXX compile features -- Detecting CXX compile features - done -- Found ament_cmake_ros: 0.10.0 (/opt/ros/humble/share/ament_cmake_ros/cmake) -- Found Python3: /usr/bin/python3 (found version "3.10.12") found components: Interpreter -- Found Python3: /usr/include/python3.10 (found version "3.10.12") found components: Development NumPy Interpreter Development.Module Development.Embed -- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.74.0/BoostConfig.cmake (found version "1.74.0") found components: python310 -- Found rclcpp: 16.0.12 (/opt/ros/humble/share/rclcpp/cmake) -- Found rosidl_generator_c: 3.1.6 (/opt/ros/humble/share/rosidl_generator_c/cmake) -- Found rosidl_adapter: 3.1.6 (/opt/ros/humble/share/rosidl_adapter/cmake) -- Found rosidl_generator_cpp: 3.1.6 (/opt/ros/humble/share/rosidl_generator_cpp/cmake) -- Using all available rosidl_typesupport_c: rosidl_typesupport_fastrtps_c;rosidl_typesupport_introspection_c -- Using all available rosidl_typesupport_cpp: rosidl_typesupport_fastrtps_cpp;rosidl_typesupport_introspection_cpp -- Found rmw_implementation_cmake: 6.1.2 (/opt/ros/humble/share/rmw_implementation_cmake/cmake) -- Found rmw_fastrtps_cpp: 6.2.7 (/opt/ros/humble/share/rmw_fastrtps_cpp/cmake) -- Found OpenSSL: /usr/lib/x86_64-linux-gnu/libcrypto.so (found version "3.0.2") -- Found FastRTPS: /opt/ros/humble/include -- Using RMW implementation 'rmw_fastrtps_cpp' as default -- Looking for pthread.h -- Looking for pthread.h - found -- Performing Test CMAKE_HAVE_LIBC_PTHREAD -- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Success -- Found Threads: TRUE -- Found sensor_msgs: 4.8.0 (/opt/ros/humble/share/sensor_msgs/cmake) -- Performing Test COMPILER_HAS_HIDDEN_VISIBILITY -- Performing Test COMPILER_HAS_HIDDEN_VISIBILITY - Success -- Performing Test COMPILER_HAS_HIDDEN_INLINE_VISIBILITY -- Performing Test COMPILER_HAS_HIDDEN_INLINE_VISIBILITY - Success -- Performing Test COMPILER_HAS_DEPRECATED_ATTR -- Performing Test COMPILER_HAS_DEPRECATED_ATTR - Success CMake Error at test/CMakeLists.txt:2 (find_package): By not providing "Findament_lint_auto.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by "ament_lint_auto", but CMake did not find one. Could not find a package configuration file provided by "ament_lint_auto" with any of the following names: ament_lint_autoConfig.cmake ament_lint_auto-config.cmake Add the installation prefix of "ament_lint_auto" to CMAKE_PREFIX_PATH or set "ament_lint_auto_DIR" to a directory containing one of the above files. If "ament_lint_auto" provides a separate development package or SDK, be sure it has been installed. -- Configuring incomplete, errors occurred! See also "/home/lzk/vision_opencv/cv_bridge/build/CMakeFiles/CMakeOutput.log"
最新发布
06-30
在构建ROS 2 C++项目时,如果遇到CMake错误提示“Could not find a package configuration file provided by `ament_lint_auto`”,则表明CMake无法找到该依赖包的配置文件。这种问题通常与ROS 2环境未正确设置、依赖项未安装或CMakeLists.txt配置有误有关。 ### 常见原因及解决方案 #### 1. 确保已正确安装ROS 2并配置了环境 `ament_lint_auto` 是ROS 2构建系统的一部分,属于`ament_cmake`工具链中的一个组件。如果ROS 2环境没有正确安装或未被激活,则可能导致此问题。 请确认是否已执行以下命令以加载ROS 2环境: ```bash source /opt/ros/humble/setup.bash # 或者对应版本如foxy、galactic等 ``` 如果使用自定义工作空间,请确保也调用了其`setup.bash`文件: ```bash source install/setup.bash ``` #### 2. 安装缺失的ROS 2依赖 如果环境中缺少`ament_lint_auto`相关的包,可以尝试通过包管理器安装: ```bash sudo apt install ros-humble-ament-lint-auto ``` 将`humble`替换为正在使用的ROS 2发行版名称(如`foxy`、`galactic`等)[^1]。 #### 3. 检查`package.xml`中是否声明了正确的依赖项 确保在`package.xml`中包含以下内容以声明对`ament_lint_auto`的构建依赖: ```xml <build_depend>ament_lint_auto</build_depend> ``` 此外,还应确保包含了`ament_cmake`作为构建依赖: ```xml <build_depend>ament_cmake</build_depend> ``` #### 4. 在`CMakeLists.txt`中正确引入ament_lint_auto 检查`CMakeLists.txt`文件是否包含以下内容: ```cmake find_package(ament_cmake REQUIRED) find_package(ament_lint_auto REQUIRED) ``` 并且在`ament_package()`之前调用了`ament_lint_auto`宏: ```cmake include_directories(include) # 其他配置... ament_lint_auto_find_test_dependencies() ament_package() ``` #### 5. 运行`rosdep`安装所有依赖 如果上述步骤未能解决问题,可尝试运行`rosdep`自动安装所有依赖: ```bash rosdep install --from-paths src --ignore-src -r -y ``` 这将解析所有`package.xml`文件,并安装缺失的依赖项。 --- ### 总结 当CMake报告找不到`ament_lint_auto`时,通常是由于ROS 2环境未正确配置、依赖未安装或`package.xml`/`CMakeLists.txt`配置不完整所致。依次检查环境变量、依赖安装状态以及构建配置文件的内容,通常能解决此问题。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值