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.

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