shared_object.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * shared_object.h - class sharedObject for use among other objects
  3. *
  4. * Copyright (c) 2006-2007 Javier Serrano Polo <jasp00/at/users.sourceforge.net>
  5. * Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
  6. *
  7. * This file is part of LMMS - https://lmms.io
  8. *
  9. * This program is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2 of the License, or (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public
  20. * License along with this program (see COPYING); if not, write to the
  21. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  22. * Boston, MA 02110-1301 USA.
  23. *
  24. */
  25. #ifndef SHARED_OBJECT_H
  26. #define SHARED_OBJECT_H
  27. #include <QtCore/QMutex>
  28. class sharedObject
  29. {
  30. public:
  31. sharedObject() :
  32. m_referenceCount( 1 ),
  33. m_lock()
  34. {
  35. }
  36. virtual ~sharedObject()
  37. {
  38. }
  39. template<class T>
  40. static T* ref( T* object )
  41. {
  42. object->m_lock.lock();
  43. // TODO: Use QShared
  44. ++object->m_referenceCount;
  45. object->m_lock.unlock();
  46. return object;
  47. }
  48. template<class T>
  49. static void unref( T* object )
  50. {
  51. object->m_lock.lock();
  52. bool deleteObject = --object->m_referenceCount <= 0;
  53. object->m_lock.unlock();
  54. if ( deleteObject )
  55. {
  56. delete object;
  57. }
  58. }
  59. // keep clang happy which complaines about unused member variable
  60. void dummy()
  61. {
  62. m_referenceCount = 0;
  63. }
  64. private:
  65. int m_referenceCount;
  66. QMutex m_lock;
  67. } ;
  68. #endif