自定义数据类型typedef和智能指针shared_ptr用法

自定义数据类型typedef和智能指针shared_ptr用法

最近在学习使用多态,多态的关键在于父类的指针或者引用指向子类,发现了一个好用的语法,智能指针,例子如下

#include <ros/ros.h>
#include <iostream>
#include "prometheus_msgs/Person.h"

using namespace std;

class father
{
    public:
    virtual void print()=0;

    int val;
   typedef  shared_ptr<father> Ptr;
 
};

class child1:public father
{
    public:
    void print()
    {
      cout<<"子1在运行"<<endl;
    }
};
class child2:public father
{
    public:
    void print()
    {
      cout<<"子2在运行"<<endl;
    }
};

int main(int argc, char** argv)
{
  ros::init(argc, argv, "test01");
  ros::NodeHandle nh("~");

  father::Ptr f;//创建了一个指向father类的一个智能指针,名字为f
  f.reset( new child1 );//f指向了chlid1类
  f->print();

  shared_ptr<father> fat;//创建了一个指向father类的一个智能指针,名字为fat
  fat.reset( new child1 );//fat指向了chlid1类
  fat->print();

  fat = make_shared<child2>();//fat指向了chlid2类
  fat->print();

  return 0;
}

运行结果:

zhu@zhu-Yoga-14sARH-2021:~$ rosrun hit test01 
子1在运行
子1在运行
子2在运行

解释

(1)typedef作用:为基本数据类型定义新的类型名

typedef  shared_ptr<father> Ptr;

也就是说,这句话的意思为定义了一个名为Ptr的数据类型(用法等效于int),这里时在类中,所以可以这样用

father::Ptr f;//创建了一个指向father类的一个智能指针,名字为f

变量f的格式是shared_ptr<father>

(2)shared_ptr<数据类型>作用:相当于指针。优点是当该指针指向新的内存时,旧内存会自动释放,用户不用管理

shared_ptr可以通过make_shared来初始化,也可以通过shared_ptr辅助函数reset方法来初始化。智能指针的用法和普通指针的用法类似,不过不需要自己管理分配的内存,对于没有初始化的指针,只能通过reset来初始化,当智能指针有值,reset会使计数器减1。智能指针可以通过重载的bool来判断是否为空。

//智能指针初始化
shared_ptr<int> p = make_shared<int>(20);
shared_ptr<int> p(new int(1));
shared_ptr<int> p1 = p;
shared_ptr<int> ptr;

//所指的对象会被重置,不带参数则是销毁
ptr.reset(new int(5));

注意:错误用法shared_ptr<int> p1 = new int(1);智能指针初始化不允许直接指向内存

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朱志远_全场最佳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值