weakptr.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* weakptr.h - An object which supports weak pointers.
  2. *
  3. * Copyright (C) 2010 Julian Andres Klode <jak@debian.org>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. * MA 02110-1301, USA.
  19. */
  20. #ifndef WEAK_POINTER_H
  21. #define WEAK_POINTER_H
  22. #include <set>
  23. /**
  24. * Class for objects providing support for weak pointers.
  25. *
  26. * This class allows for the registration of certain pointers as weak,
  27. * which will cause them to be set to NULL when the destructor of the
  28. * object is called.
  29. */
  30. class WeakPointable {
  31. private:
  32. std::set<WeakPointable**> pointers;
  33. public:
  34. /**
  35. * Add a new weak pointer.
  36. */
  37. inline void AddWeakPointer(WeakPointable** weakptr) {
  38. pointers.insert(weakptr);
  39. }
  40. /**
  41. * Remove the weak pointer from the list of weak pointers.
  42. */
  43. inline void RemoveWeakPointer(WeakPointable **weakptr) {
  44. pointers.erase(weakptr);
  45. }
  46. /**
  47. * Deconstruct the object, set all weak pointers to NULL.
  48. */
  49. ~WeakPointable() {
  50. std::set<WeakPointable**>::iterator iter = pointers.begin();
  51. while (iter != pointers.end())
  52. **(iter++) = NULL;
  53. }
  54. };
  55. #endif // WEAK_POINTER_H