fork download
  1. #include <vector>
  2. #include <memory>
  3.  
  4. using std::vector;
  5. using std::unique_ptr;
  6. using std::move;
  7.  
  8. /// gameobjec base class
  9. class gameobject
  10. {
  11. public:
  12. virtual ~gameobject() {};
  13. };
  14.  
  15. /// player class
  16. class player: public gameobject
  17. {
  18. public:
  19. float* some_data;
  20.  
  21. player(int map_size)
  22. {
  23. some_data = new float[map_size];
  24. }
  25.  
  26. ~player()
  27. {
  28. delete[] some_data;
  29. }
  30. };
  31.  
  32. /// handler class
  33. class handler
  34. {
  35. public:
  36. vector<gameobject*> objects;
  37. vector<unique_ptr<gameobject> > objects_auto;
  38.  
  39. void addobject(gameobject* object)
  40. {
  41. objects.push_back(object);
  42. }
  43.  
  44.  
  45. void addobject(unique_ptr<gameobject>& object)
  46. {
  47. objects_auto.push_back(move(object));
  48. }
  49.  
  50. void add_raw_to_auto(gameobject* object)
  51. {
  52. objects_auto.push_back(unique_ptr<gameobject>(object));
  53. }
  54.  
  55. ~handler()
  56. {
  57. // objects behind raw pointers must be explicitly deleted
  58. for(auto obj: objects)
  59. delete obj;
  60.  
  61. // nothing needs to be done about unique_ptr containers
  62. }
  63. };
  64.  
  65. int main()
  66. {
  67. handler* hand = new handler();
  68.  
  69. for(int i=0; i<100; ++i)
  70. {
  71. // add raw pointer to a collection of raw pointers
  72. gameobject* pla = new player(i);
  73. hand->addobject(pla);
  74.  
  75. // add unique_ptr to a collection of unique_ptr
  76. unique_ptr<gameobject> pla_auto(new player(i*2));
  77. hand->addobject(pla_auto);
  78.  
  79. // add raw pointer to a collection of unique ptr
  80. gameobject* pla_raw = new player(i);
  81. hand->add_raw_to_auto(pla_raw);
  82. }
  83.  
  84. delete hand;
  85. }
  86.  
  87.  
Success #stdin #stdout 0s 4392KB
stdin
Standard input is empty
stdout
Standard output is empty