Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4462395
  • 博文数量: 356
  • 博客积分: 10458
  • 博客等级: 上将
  • 技术积分: 4734
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-24 14:59
文章分类

全部博文(356)

文章存档

2020年(17)

2019年(9)

2018年(26)

2017年(5)

2016年(11)

2015年(20)

2014年(2)

2013年(17)

2012年(15)

2011年(4)

2010年(7)

2009年(14)

2008年(209)

分类: C/C++

2018-09-21 12:24:00

需求:

多种继承类/子类 对象共同存放于容器中, 要求能push进不同对象,pop出来后能实现多态。

实现分析:

这种情况就得容器中存放基类指针,但是存放指针就意味着得自己管理内存,主动释放。 有没有方法让c++自己去管理呢,答案是用智能指针。

示例代码: 容器中存放的是unique_ptr, pop出来后可以转成shared_ptr给外界去调用。超级方便

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <list>
  4. #include <memory>
  5. #include <iostream>

  6. using namespace std;

  7. class Base
  8. {
  9. public:
  10.     Base();
  11.     ~Base();

  12.     virtual void Func();
  13. };

  14. Base::Base()
  15. {
  16.     printf( "%s\n", __func__ );
  17. }

  18. Base::~Base()
  19. {
  20.     printf( "%s\n", __func__ );
  21. }

  22. void Base::Func()
  23. {
  24.     printf( "base::%s\n", __func__ );
  25. }

  26. class Drived : public Base
  27. {
  28. public:
  29.     Drived();
  30.     ~Drived();

  31.     virtual void Func();
  32. };

  33. Drived::Drived()
  34. {
  35.     printf( "%s\n", __func__ );
  36. }

  37. Drived::~Drived()
  38. {
  39.     printf( "%s\n", __func__ );
  40. }

  41. void Drived::Func()
  42. {
  43.     printf( "drived:%s\n", __func__ );
  44. }

  45. template<typename T, typename... Ts>
  46. std::unique_ptr<T> make_unique(Ts&&... params)
  47. {
  48.     return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
  49. }

  50. std::list<std::unique_ptr<Base> > myList;

  51. template<typename T>
  52. void Push(const T &base)
  53. {
  54.     myList.push_back(make_unique<T> (std::move(base)));
  55. }

  56. void Pop()
  57. {
  58.     //std:unique_ptr<Base> ptr = std::move(myList.front());
  59.     std::shared_ptr<Base> ptr = std::move(myList.front());
  60.     ptr->Func();
  61.     myList.pop_front();
  62. }


  63.     int
  64. main( int argc, char **argv )
  65. {
  66.     Drived drived;
  67.     Push(drived);
  68.     Pop();

  69.     return 0;
  70. }

编译请加--std=c++11

输出:

./a.out                  
Base
Drived
drived:Func
~Base
~Drived
~Base

作者:帅得不敢出门    c++哈哈堂 31843264








阅读(2954) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~