Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

359 lines
14KB

  1. /*
  2. * Carla misc utils imported from Juce source code
  3. * Copyright (C) 2004-11 Raw Material Software Ltd.
  4. * Copyright (C) 2013 Filipe Coelho <falktx@falktx.com>
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License as
  8. * published by the Free Software Foundation; either version 2 of
  9. * the License, or any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * For a full copy of the GNU General Public License see the GPL.txt file
  17. */
  18. #ifndef __CARLA_JUCE_UTILS_HPP__
  19. #define __CARLA_JUCE_UTILS_HPP__
  20. #include "CarlaUtils.hpp"
  21. #include <algorithm>
  22. #define CARLA_DECLARE_NON_COPYABLE(className) \
  23. className (const className&);\
  24. className& operator= (const className&);
  25. /** This is a shorthand way of writing both a CARLA_DECLARE_NON_COPYABLE and
  26. CARLA_LEAK_DETECTOR macro for a class.
  27. */
  28. #define CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(className) \
  29. CARLA_DECLARE_NON_COPYABLE(className) \
  30. CARLA_LEAK_DETECTOR(className)
  31. /** This macro can be added to class definitions to disable the use of new/delete to
  32. allocate the object on the heap, forcing it to only be used as a stack or member variable.
  33. */
  34. #define CARLA_PREVENT_HEAP_ALLOCATION \
  35. private: \
  36. static void* operator new (size_t); \
  37. static void operator delete (void*);
  38. /** A good old-fashioned C macro concatenation helper.
  39. This combines two items (which may themselves be macros) into a single string,
  40. avoiding the pitfalls of the ## macro operator.
  41. */
  42. #define CARLA_JOIN_MACRO_HELPER(a, b) a ## b
  43. #define CARLA_JOIN_MACRO(item1, item2) CARLA_JOIN_MACRO_HELPER (item1, item2)
  44. //==============================================================================
  45. /**
  46. Embedding an instance of this class inside another class can be used as a low-overhead
  47. way of detecting leaked instances.
  48. This class keeps an internal static count of the number of instances that are
  49. active, so that when the app is shutdown and the static destructors are called,
  50. it can check whether there are any left-over instances that may have been leaked.
  51. To use it, use the CARLA_LEAK_DETECTOR macro as a simple way to put one in your
  52. class declaration. Have a look through the juce codebase for examples, it's used
  53. in most of the classes.
  54. */
  55. template <class OwnerClass>
  56. class LeakedObjectDetector
  57. {
  58. public:
  59. //==============================================================================
  60. LeakedObjectDetector()
  61. {
  62. ++(getCounter().numObjects);
  63. }
  64. LeakedObjectDetector(const LeakedObjectDetector&)
  65. {
  66. ++(getCounter().numObjects);
  67. }
  68. ~LeakedObjectDetector()
  69. {
  70. if (--(getCounter().numObjects) < 0)
  71. {
  72. carla_stderr("*** Dangling pointer deletion! Class: '%s'", getLeakedObjectClassName());
  73. /** If you hit this, then you've managed to delete more instances of this class than you've
  74. created.. That indicates that you're deleting some dangling pointers.
  75. Note that although this assertion will have been triggered during a destructor, it might
  76. not be this particular deletion that's at fault - the incorrect one may have happened
  77. at an earlier point in the program, and simply not been detected until now.
  78. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  79. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  80. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  81. */
  82. assert(false);
  83. }
  84. }
  85. private:
  86. //==============================================================================
  87. class LeakCounter
  88. {
  89. public:
  90. LeakCounter()
  91. {
  92. numObjects = 0;
  93. }
  94. ~LeakCounter()
  95. {
  96. if (numObjects > 0)
  97. {
  98. carla_stderr("*** Leaked objects detected: %i instance(s) of class '%s'", numObjects, getLeakedObjectClassName());
  99. /** If you hit this, then you've leaked one or more objects of the type specified by
  100. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  101. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  102. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  103. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  104. */
  105. assert(false);
  106. }
  107. }
  108. int numObjects;
  109. };
  110. static const char* getLeakedObjectClassName()
  111. {
  112. return OwnerClass::getLeakedObjectClassName();
  113. }
  114. static LeakCounter& getCounter()
  115. {
  116. static LeakCounter counter;
  117. return counter;
  118. }
  119. };
  120. #define CARLA_LEAK_DETECTOR(OwnerClass) \
  121. friend class LeakedObjectDetector<OwnerClass>; \
  122. static const char* getLeakedObjectClassName() { return #OwnerClass; } \
  123. LeakedObjectDetector<OwnerClass> CARLA_JOIN_MACRO (leakDetector, __LINE__);
  124. //==============================================================================
  125. /**
  126. This class holds a pointer which is automatically deleted when this object goes
  127. out of scope.
  128. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  129. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  130. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  131. created objects.
  132. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  133. to an object. If you use the assignment operator to assign a different object to a
  134. ScopedPointer, the old one will be automatically deleted.
  135. Important note: The class is designed to hold a pointer to an object, NOT to an array!
  136. It calls delete on its payload, not delete[], so do not give it an array to hold! For
  137. that kind of purpose, you should be using HeapBlock or Array instead.
  138. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  139. object to which it points during its lifetime. This means that making a copy of a const
  140. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  141. old one.
  142. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  143. can use the release() method.
  144. Something to note is the main difference between this class and the std::auto_ptr class,
  145. which is that ScopedPointer provides a cast-to-object operator, wheras std::auto_ptr
  146. requires that you always call get() to retrieve the pointer. The advantages of providing
  147. the cast is that you don't need to call get(), so can use the ScopedPointer in pretty much
  148. exactly the same way as a raw pointer. The disadvantage is that the compiler is free to
  149. use the cast in unexpected and sometimes dangerous ways - in particular, it becomes difficult
  150. to return a ScopedPointer as the result of a function. To avoid this causing errors,
  151. ScopedPointer contains an overloaded constructor that should cause a syntax error in these
  152. circumstances, but it does mean that instead of returning a ScopedPointer from a function,
  153. you'd need to return a raw pointer (or use a std::auto_ptr instead).
  154. */
  155. template <class ObjectType>
  156. class ScopedPointer
  157. {
  158. public:
  159. //==============================================================================
  160. /** Creates a ScopedPointer containing a null pointer. */
  161. ScopedPointer()
  162. : object(nullptr)
  163. {
  164. }
  165. /** Creates a ScopedPointer that owns the specified object. */
  166. ScopedPointer(ObjectType* const objectToTakePossessionOf)
  167. : object(objectToTakePossessionOf)
  168. {
  169. }
  170. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  171. Because a pointer can only belong to one ScopedPointer, this transfers
  172. the pointer from the other object to this one, and the other object is reset to
  173. be a null pointer.
  174. */
  175. ScopedPointer(ScopedPointer& objectToTransferFrom)
  176. : object(objectToTransferFrom.object)
  177. {
  178. objectToTransferFrom.object = nullptr;
  179. }
  180. /** Destructor.
  181. This will delete the object that this ScopedPointer currently refers to.
  182. */
  183. ~ScopedPointer()
  184. {
  185. delete object;
  186. }
  187. /** Changes this ScopedPointer to point to a new object.
  188. Because a pointer can only belong to one ScopedPointer, this transfers
  189. the pointer from the other object to this one, and the other object is reset to
  190. be a null pointer.
  191. If this ScopedPointer already points to an object, that object
  192. will first be deleted.
  193. */
  194. ScopedPointer& operator=(ScopedPointer& objectToTransferFrom)
  195. {
  196. if (this != objectToTransferFrom.getAddress())
  197. {
  198. // Two ScopedPointers should never be able to refer to the same object - if
  199. // this happens, you must have done something dodgy!
  200. assert(object == nullptr || object != objectToTransferFrom.object);
  201. ObjectType* const oldObject = object;
  202. object = objectToTransferFrom.object;
  203. objectToTransferFrom.object = nullptr;
  204. delete oldObject;
  205. }
  206. return *this;
  207. }
  208. /** Changes this ScopedPointer to point to a new object.
  209. If this ScopedPointer already points to an object, that object
  210. will first be deleted.
  211. The pointer that you pass in may be a nullptr.
  212. */
  213. ScopedPointer& operator=(ObjectType* const newObjectToTakePossessionOf)
  214. {
  215. if (object != newObjectToTakePossessionOf)
  216. {
  217. ObjectType* const oldObject = object;
  218. object = newObjectToTakePossessionOf;
  219. delete oldObject;
  220. }
  221. return *this;
  222. }
  223. //==============================================================================
  224. /** Returns the object that this ScopedPointer refers to. */
  225. operator ObjectType*() const { return object; }
  226. /** Returns the object that this ScopedPointer refers to. */
  227. ObjectType* get() const { return object; }
  228. /** Returns the object that this ScopedPointer refers to. */
  229. ObjectType& operator*() const { return *object; }
  230. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  231. ObjectType* operator->() const { return object; }
  232. //==============================================================================
  233. /** Removes the current object from this ScopedPointer without deleting it.
  234. This will return the current object, and set the ScopedPointer to a null pointer.
  235. */
  236. ObjectType* release()
  237. {
  238. ObjectType* const o = object;
  239. object = nullptr;
  240. return o;
  241. }
  242. //==============================================================================
  243. /** Swaps this object with that of another ScopedPointer.
  244. The two objects simply exchange their pointers.
  245. */
  246. void swapWith(ScopedPointer<ObjectType>& other)
  247. {
  248. // Two ScopedPointers should never be able to refer to the same object - if
  249. // this happens, you must have done something dodgy!
  250. assert(object != other.object || this == other.getAddress());
  251. std::swap(object, other.object);
  252. }
  253. private:
  254. //==============================================================================
  255. ObjectType* object;
  256. // (Required as an alternative to the overloaded & operator).
  257. const ScopedPointer* getAddress() const
  258. {
  259. return this;
  260. }
  261. #if ! defined(CARLA_CC_MSVC) // (MSVC can't deal with multiple copy constructors)
  262. /* These are private to stop people accidentally copying a const ScopedPointer (the compiler
  263. would let you do so by implicitly casting the source to its raw object pointer).
  264. A side effect of this is that you may hit a puzzling compiler error when you write something
  265. like this:
  266. ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private.
  267. Even though the compiler would normally ignore the assignment here, it can't do so when the
  268. copy constructor is private. It's very easy to fix though - just write it like this:
  269. ScopedPointer<MyClass> m (new MyClass()); // Compiles OK
  270. It's good practice to always use the latter form when writing your object declarations anyway,
  271. rather than writing them as assignments and assuming (or hoping) that the compiler will be
  272. smart enough to replace your construction + assignment with a single constructor.
  273. */
  274. ScopedPointer(const ScopedPointer&);
  275. ScopedPointer& operator=(const ScopedPointer&);
  276. #endif
  277. };
  278. //==============================================================================
  279. /** Compares a ScopedPointer with another pointer.
  280. This can be handy for checking whether this is a null pointer.
  281. */
  282. template <class ObjectType>
  283. bool operator==(const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  284. {
  285. return static_cast<ObjectType*>(pointer1) == pointer2;
  286. }
  287. /** Compares a ScopedPointer with another pointer.
  288. This can be handy for checking whether this is a null pointer.
  289. */
  290. template <class ObjectType>
  291. bool operator!=(const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  292. {
  293. return static_cast<ObjectType*>(pointer1) != pointer2;
  294. }
  295. #endif // __CARLA_JUCE_UTILS_HPP__