【C++/Boost Lib】如何初始化一个shared_ptr指针。

本文详细解析了C++中boost::shared_ptr类在处理Map或Set元素时,如何通过默认构造函数实现空初始化,并讨论了这种设计方法背后的原理及其在实际开发中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    shared_ptr指针带有有参数的构造函数。对于通常的定义,不需要显示的初始化。其构造函数代码如下:
template<class T> class shared_ptr
{
public:

    explicit shared_ptr(T * p = 0): px(p)
    { 
        //Snip
    }

    //...

private:

    T * px;            // contained pointer
    count_type * pn;   // ptr to reference counter
};

但是,如果是Map或者Set的元素,则需要提供显示的初始值。(一般是“空值”。)提供这种初值的方法是boost::shared_ptr<class T> ()。

这种初始化的方法是C++中常见的一种设计方法:给构造函数一个default值,然后,在需要空值的时候,用一个临时变量来初始化。

注意:不能直接使用NULL或者0来初始化。

cc1plus: warning: ‘-Wabi’ won’t warn about anything [-Wabi] cc1plus: note: ‘-Wabi’ warns about differences from the most up-to-date ABI, which is also used by default cc1plus: note: use e.g. ‘-Wabi=11’ to warn about changes from GCC 7 In file included from /usr/include/boost/detail/endian.hpp:9, from /home/csh/pcl-1.8.1/common/include/pcl/PCLPointCloud2.h:11, from /home/csh/pcl-1.8.1/common/include/pcl/pcl_base.h:55, from /home/csh/pcl-1.8.1/segmentation/include/pcl/segmentation/organized_multi_plane_segmentation.h:44, from /home/csh/pcl-1.8.1/segmentation/src/organized_multi_plane_segmentation.cpp:42: /usr/include/boost/predef/detail/endian_compat.h:11:161: note: #pragma message: The use of BOOST_*_ENDIAN and BOOST_BYTE_ORDER is deprecated. Please include <boost/predef/other/endian.h> and use BOOST_ENDIAN_*_BYTE instead 11 | t/predef/other/endian.h> and use BOOST_ENDIAN_*_BYTE instead") | ^ In file included from /home/csh/pcl-1.8.1/segmentation/include/pcl/segmentation/organized_multi_plane_segmentation.h:48, from /home/csh/pcl-1.8.1/segmentation/src/organized_multi_plane_segmentation.cpp:42: /home/csh/pcl-1.8.1/segmentation/include/pcl/segmentation/plane_coefficient_comparator.h: In member function ‘const std::vector<float>& pcl::PlaneCoefficientComparator<PointT, PointNT>::getPlaneCoeffD() const’: /home/csh/pcl-1.8.1/segmentation/include/pcl/segmentation/plane_coefficient_comparator.h:144:17: error: invalid initialization of reference of type ‘const std::vector<float>&’ from expression of type ‘const boost::shared_ptr<std::vector<float> >’ 144 | return (plane_coeff_d_); | ~^~~~~~~~~~~~~~~ make[2]: *** [segmentation/CMakeFiles/pcl_segmentation.dir/build.make:167:segmentation/CMakeFiles/pcl_segmentation.dir/src/organized_multi_plane_segmentation.cpp.o] 错误 1 make[1]: *** [CMakeFiles/Makefile2:1905:segmentation/CMakeFiles/pcl_segmentation.dir/all] 错误 2 make: *** [Makefile:163:all] 错误 2
最新发布
03-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值