code_junkie

Erase all members of a class

Nov 14th, 2011
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. class a_class
  2. {
  3. public:
  4. a_class() {...}
  5. int some_method(int some_param) {...}
  6.  
  7. int value_1;
  8. int value_2;
  9. float value_3;
  10. std::vector<some_other_class*> even_more_values;
  11. /* and so on */
  12. }
  13.  
  14. a_class a_instances[10];
  15.  
  16. void some_function()
  17. {
  18. do_stuff();
  19. do_more_stuff();
  20.  
  21. memset(a_instances, 0, 10 * sizeof(a_class)); // <===== WTF?
  22. }
  23.  
  24. ...
  25. for(size_t i=0; i < 10; i++)
  26. objects[i].clear();
  27.  
  28. void clear() {
  29. a_object o;
  30. o.swap(*this);
  31. }
  32.  
  33. void clear()
  34. {
  35. value1=0;
  36. value2=0;
  37. value_3=0f;
  38. even_more_values.clear();
  39. }
  40.  
  41. class a_class
  42. {
  43. public:
  44. a_class() {...}
  45. ~a_class() { /* make sure that even_more_values gets cleaned up properly */ }
  46.  
  47. int some_method(int some_param) {...}
  48.  
  49. int value_1;
  50. int value_2;
  51. float value_3;
  52. std::vector<some_other_class*> even_more_values;
  53. /* and so on */
  54. }
  55.  
  56. void some_function()
  57. {
  58. std::vector<a_class> a_instances( 10 );
  59.  
  60. // Pass a_instances into these functions by reference rather than by using
  61. // a global. This is re-entrant and more likely to be thread-safe.
  62. do_stuff( a_instances );
  63. do_more_stuff( a_instances );
  64.  
  65. // a_instances will be cleaned up automatically here. This also allows you some
  66. // weak exception safety.
  67. }
Add Comment
Please, Sign In to add comment