c++-gtk-utils
shared_handle.h
Go to the documentation of this file.
1 /* Copyright (C) 2004 to 2013 Chris Vine
2 
3 The library comprised in this file or of which this file is part is
4 distributed by Chris Vine under the GNU Lesser General Public
5 License as follows:
6 
7  This library is free software; you can redistribute it and/or
8  modify it under the terms of the GNU Lesser General Public License
9  as published by the Free Software Foundation; either version 2.1 of
10  the License, or (at your option) any later version.
11 
12  This library is distributed in the hope that it will be useful, but
13  WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  Lesser General Public License, version 2.1, for more details.
16 
17  You should have received a copy of the GNU Lesser General Public
18  License, version 2.1, along with this library (see the file LGPL.TXT
19  which came with this source code package in the c++-gtk-utils
20  sub-directory); if not, write to the Free Software Foundation, Inc.,
21  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 
23 However, it is not intended that the object code of a program whose
24 source code instantiates a template from this file or uses macros or
25 inline functions (of any length) should by reason only of that
26 instantiation or use be subject to the restrictions of use in the GNU
27 Lesser General Public License. With that in mind, the words "and
28 macros, inline functions and instantiations of templates (of any
29 length)" shall be treated as substituted for the words "and small
30 macros and small inline functions (ten lines or less in length)" in
31 the fourth paragraph of section 5 of that licence. This does not
32 affect any other reason why object code may be subject to the
33 restrictions in that licence (nor for the avoidance of doubt does it
34 affect the application of section 2 of that licence to modifications
35 of the source code in this file).
36 
37 */
38 
39 #ifndef CGU_SHARED_HANDLE_H
40 #define CGU_SHARED_HANDLE_H
41 
42 // define this if, instead of GLIB atomic funcions/memory barriers,
43 // you want to use a (slower) mutex to lock the reference count in the
44 // SharedLockHandle class
45 /* #define CGU_SHARED_LOCK_HANDLE_USE_MUTEX 1 */
46 
47 #include <exception>
48 #include <new>
49 #include <functional> // for std::less and std::hash<T*>
50 #include <utility> // for std::swap
51 #include <cstddef> // for std::size_t
52 #include <cstdlib>
53 
54 #include <glib.h>
55 
56 #ifdef CGU_SHARED_LOCK_HANDLE_USE_MUTEX
57 #include <c++-gtk-utils/mutex.h>
58 #endif
59 
61 
62 /**
63  * @addtogroup handles handles and smart pointers
64  */
65 
66 namespace Cgu {
67 
68 /**
69  * @class SharedHandle shared_handle.h c++-gtk-utils/shared_handle.h
70  * @brief This is a generic class for managing the lifetime of objects
71  * allocated on freestore.
72  * @ingroup handles
73  * @sa SharedLockHandle
74  * @sa ScopedHandle
75  * @sa SharedHandleError
76  * @sa GcharSharedHandle
77  * @sa GerrorSharedHandle
78  * @sa StandardArrayDelete CFree GFree GerrorFree GSliceFree GSliceFreeSize GSliceDestroy
79  *
80  * The SharedHandle class is similar to the SharedPtr class (it keeps
81  * a reference count and deletes the handled object when the count
82  * reaches 0), but it does not have pointer semantics. Accordingly,
83  * it can be used to manage the memory of arrays and other objects
84  * allocated on the heap.
85  *
86  * Because it is useful with arrays, by default it deallocates memory
87  * using C++ delete[]. However, if a SharedHandle object is passed a
88  * function object type as a second template argument when
89  * instantiated, it will use that function object to delete memory.
90  * This enables it to handle the memory of any object, such as objects
91  * to be deleted using std::free() or Glib's g_free(), g_list_free()
92  * or g_slice_free(). Instances (such as @ref GcharScopedHandleAnchor
93  * "GcharScopedHandle", @ref GcharSharedHandleAnchor
94  * "GcharSharedHandle", @ref GerrorSharedHandleAnchor
95  * "GerrorSharedHandle" and @ref GerrorScopedHandleAnchor
96  * "GerrorScopedHandle") typdef'ed for particular deleters can
97  * conveniently manage objects of any kind.
98  *
99  * To reflect the fact that it is just a handle for a pointer, it has
100  * different instantiation semantics from a SharedPtr object. A
101  * SharedPtr object is instantiated using this syntax:
102  *
103  * @code SharedPtr<ObjType> sh_ptr(new ObjType); @endcode
104  *
105  * A SharedHandle is instantiated using this syntax (note that the
106  * instantiated handle is for type T* and not T):
107  *
108  * @code SharedHandle<ObjType*> sh_handle(new ObjType[n]); @endcode
109  *
110  *
111  * Apart from the operatorT() type conversion operator (which returns
112  * the underlying pointer), the only other method to obtain the
113  * underlying pointer is the get() method. If the object referenced
114  * is an array allocated on the heap, to use indexing you could either
115  * do this:
116  *
117  * @code
118  * using namespace Cgu;
119  * SharedHandle<char*> handle(new char[10]);
120  * handle.get()[0] = 'a';
121  * std::cout << handle.get()[0] << std::endl;
122  * @endcode
123  *
124  * or this:
125  *
126  * @code
127  * using namespace Cgu;
128  * SharedHandle<char*> handle(new char[10]);
129  * handle[0] = 'a';
130  * std::cout << handle[0] << std::endl;
131  * @endcode
132  *
133  * There is also a SharedLockHandle class, which has a thread-safe
134  * reference count, and a ScopedHandle class, which deletes its object
135  * as soon as it goes out of scope. A ScopedHandle class can be
136  * viewed as a SharedHandle which cannot be assigned to or used as the
137  * argument to a copy constructor and therefore which cannot have a
138  * reference count of more than 1. It is used where, if you wanted
139  * pointer semantics, you might use a const std::auto_ptr<>.
140  *
141  * SharedHandle objects can be instantiated for pointers to constant
142  * objects (such as SharedHandle<const char*>), provided the deleter
143  * functor will take such pointers.
144  *
145  * This library provides StandardArrayDelete, CFree, GFree,
146  * GerrorFree, GSliceFree, GSliceFreeSize and GSliceDestroy deleter
147  * functors, which can be used as the second template parameter of the
148  * SharedHandle class. As mentioned above, StandardArrayDelete is the
149  * default, and some typedef'ed instances of SharedHandle for gchar
150  * (with the GFree deleter) and for GError (with the GerrorFree
151  * deleter) are provided.
152  *
153  * @b Comparison @b with @b std::shared_ptr
154  *
155  * Although the semantics of std::shared_ptr in C++11 are not
156  * particularly suited to managing either arrays or C objects with
157  * accessor functions (such as in glib), most of the things that can
158  * be done by this class can be done by using std::shared_ptr with a
159  * specialised deleter. However, this class is retained in the
160  * c++-gtk-utils library not only to retain compatibility with series
161  * 1.2 of the library, but also to cater for some cases not met (or
162  * not so easily met) by std::shared_ptr:
163  *
164  * 1. The Cgu::SharedHandle class takes its deleter as a template
165  * parameter, which means that typedefs can be used to enable
166  * handles for particular deleters to be easily created (and as
167  * mentioned, this library provides a number of pre-formed deleter
168  * functors and typedefs for them). With std::shared_ptr, custom
169  * deleters must be passed to the shared_ptr constructor on every
170  * occasion a shared_ptr is constructed to manage a new object (and
171  * they cannot be templated as a typedef).
172  * 2. Glib memory slices provide an efficient small object allocator
173  * (they are likely to be significantly more efficient than global
174  * operator new()/new[](), which generally hand off to malloc(),
175  * and whilst malloc() is good for large block allocations it is
176  * generally poor as a small object allocator). Internal
177  * Cgu::SharedHandle allocation using glib memory slices can be
178  * achieved by compiling the library with the
179  * \--with-glib-memory-slices-no-compat configuration option.
180  * 3. If glib memory slices are not used (which do not throw),
181  * constructing a shared pointer for a new managed object (or
182  * calling reset() for a new managed object) might throw if
183  * internal allocation fails. Although by default the
184  * Cgu::SharedHandle implementation will delete the new managed
185  * object in such a case, it also provides an alternative
186  * constructor and reset() method which instead enable the new
187  * object to be accessed via the thrown exception object so that
188  * user code can decide what to do; std::shared_ptr deletes the new
189  * object in every case.
190  * 4. A user can explicitly state whether the shared handle object is
191  * to have atomic increment and decrement-and-test with respect to
192  * the reference count so that the reference count is thread safe
193  * ('no' in the case of Cgu::SharedHandle, and 'yes' in the case of
194  * Cgu::SharedLockHandle). Using atomic functions is unnecessary
195  * if the managed object concerned is only addressed in one thread
196  * (and might cause unwanted cache flushing in certain
197  * circumstances). std::shared_ptr will generally always use
198  * atomic functions with respect to its reference count in a
199  * multi-threaded program.
200  *
201  * In favour of std::shared_ptr, it has an associated std::weak_ptr
202  * class, which Cgu::SharedHandle does not (there is a
203  * Cgu::GobjWeakHandle class, but that is cognate with Cgu::GobjHandle
204  * and is only usable with GObjects).
205  *
206  * If the library is compiled with the
207  * \--with-glib-memory-slices-no-compat configuration option, as
208  * mentioned Cgu::SharedHandle constructs its reference counting
209  * internals using glib memory slices. Although it is safe in a
210  * multi-threaded program if glib < 2.32 is installed to construct a
211  * static SharedHandle object in global namespace (that is, prior to
212  * g_thread_init() being called) by means of the default constructor
213  * and/or a pointer argument of NULL, it is not safe if constructed
214  * with a non-NULL pointer value. If glib >= 2.32 is installed,
215  * global objects with memory slices are safe in all
216  * circumstances. (Having said that, it would be highly unusual to
217  * have global SharedHandle objects.)
218  */
219 
220 /********************* here are some deleter classes *******************/
221 
222 /**
223  * @class StandardArrayDelete shared_handle.h c++-gtk-utils/shared_handle.h
224  * @brief A deleter functor for use as the second (Dealloc) template
225  * parameter of the SharedHandle, SharedLockHandle or ScopedHandle
226  * template classes, which calls the C++ delete[] expression.
227  * @ingroup handles
228  * @details This functor enables those classes to manage arrays
229  * created with the new expression. It is the default type of the
230  * second template paramenter of those classes.
231  */
232 template <class T> class StandardArrayDelete {
233 public:
234  void operator()(T obj) {
235  delete[] obj;
236  }
237 };
238 
239 /**
240  * @class CFree shared_handle.h c++-gtk-utils/shared_handle.h
241  * @brief A deleter functor for use as the second (Dealloc) template
242  * parameter of the SharedHandle, SharedLockHandle or ScopedHandle
243  * template classes, which calls std::free.
244  * @ingroup handles
245  * @details This functor enables those classes to manage memory
246  * allocated with std::malloc(), std::calloc() and std::realloc().
247  */
248 class CFree {
249 public:
250  void operator()(const void* obj) {
251  std::free(const_cast<void*>(obj));
252  }
253 };
254 
255 /**
256  * @class GFree shared_handle.h c++-gtk-utils/shared_handle.h
257  * @brief A deleter functor for use as the second (Dealloc) template
258  * parameter of the SharedHandle, SharedLockHandle or ScopedHandle
259  * template classes, which calls glib's g_free().
260  * @ingroup handles
261  * @details This functor enables those classes to manage memory
262  * allocated by glib or gtk+ functions which requires to be freed with
263  * g_free(). It is used in the typedefs @ref GcharSharedHandleAnchor
264  * "GcharSharedHandle" and @ref GcharScopedHandleAnchor
265  * "GcharScopedHandle".
266  */
267 class GFree {
268 public:
269  void operator()(const void* obj) {
270  g_free(const_cast<void*>(obj));
271  }
272 };
273 
274 /**
275  * @class GSliceFree shared_handle.h c++-gtk-utils/shared_handle.h
276  * @brief A deleter functor for use as the second (Dealloc) template
277  * parameter of the SharedHandle, SharedLockHandle or ScopedHandle
278  * template classes, which calls glib's g_slice_free1().
279  * @ingroup handles
280  *
281  * @details This functor enables those classes to manage a memory
282  * block allocated using glib memory slices. The managed memory block
283  * to be deleted by the GSliceFree functor must have the same size as
284  * the size of the object for which the functor is instantiated by
285  * pointer, as for example as allocated with the g_slice_new,
286  * g_slice_new0 or g_slice_dup macros (in other words, the GSliceFree
287  * template parameter must match the argument passed to those macros):
288  * see the example below. Use GSliceFreeSize where it is necessary or
289  * more convenient to have the size of the block to be freed as the
290  * template parameter. Use GSliceDestroy where the memory holds a C++
291  * object constructed in the memory by the global placement new
292  * expression.
293  *
294  * The type of the template argument for the functor is a pointer to
295  * the managed type: it is the same as the first template argument of
296  * the relevant SharedHandle, SharedLockHandle or ScopedHandle object.
297  * For example:
298  *
299  * @code
300  * using namespace Cgu;
301  * SharedHandle<MyStruct*, GSliceFree<MyStruct*> > h(g_slice_new(MyStruct));
302  * ...
303  * @endcode
304  *
305  * The availability of this functor is not dependent on the library
306  * having been installed with the \--with-glib-memory-slices-compat or
307  * \--with-glib-memory-slices-no-compat configuration option (see @ref
308  * Memory for further details of those options).
309  */
310 template <class T> class GSliceFree {
311 public:
312  void operator()(T obj) {
313  g_slice_free1(sizeof(*obj), (void*)obj);
314  }
315 };
316 
317 /**
318  * @class GSliceDestroy shared_handle.h c++-gtk-utils/shared_handle.h
319  * @brief A deleter functor for use as the second (Dealloc) template
320  * parameter of the SharedHandle, SharedLockHandle or ScopedHandle
321  * template classes, which calls glib's g_slice_free1(), but before
322  * doing so also explicitly calls the destructor of a C++ object
323  * constructed in the memory.
324  * @ingroup handles
325  *
326  * @details The managed memory block to be deleted by the
327  * GSliceDestroy functor must have the same size as the size of the
328  * object for which the functor is instantiated by pointer, as for
329  * example as allocated with the g_slice_new or g_slice_new0 macros
330  * (in other words, the GSliceDestroy template parameter must match
331  * the argument passed to those macros), and the memory block must
332  * have had that object constructed in it with the global placement
333  * new expression: see the example below. Sometimes it is more
334  * convenient to implement C++ objects in glib memory slices that way,
335  * rather than to have custom new and delete member operators of the
336  * classes concerned which use glib's g_slice_*(). However, a
337  * SharedHandle class with a GSliceDestroy deleter is not as easy to
338  * use as the SharedPtr class, as SharedHandle has no operator*() nor
339  * operator->() method (the get() method would have to be used to
340  * obtain the underlying pointer).
341  *
342  * One consequence of the static sizing (and so typing) of memory
343  * slices is that a GSliceDestroy object instantiated for the
344  * management of a particular class must not be used by a
345  * SharedHandle, SharedLockHandle or ScopedHandle object which
346  * attempts to manage a class derived from it. This comes back to the
347  * point that the GSliceDestroy template parameter must match the
348  * argument passed to the g_slice_new or g_slice_new0 macros.
349  *
350  * The type of the template argument for the functor is a pointer to
351  * the managed type: it is the same as the first template argument of
352  * the relevant SharedHandle, SharedLockHandle or ScopedHandle object.
353  * For example, to construct a SharedHandle managing an object of type
354  * MyClass to be constructed in a glib memory slice in an exception
355  * safe way:
356  *
357  * @code
358  * using namespace Cgu;
359  * SharedHandle<MyClass*, GSliceDestroy<MyClass*> > h; // won't throw
360  * { // scope block for p variable
361  * MyClass* p = g_slice_new(MyClass);
362  * try {new(p) MyClass;} // MyClass constructor might throw
363  * catch(...) {
364  * g_slice_free(MyClass, p);
365  * throw;
366  * }
367  * h.reset(p); // might throw but if so cleans up
368  * }
369  * ...
370  * @endcode
371  *
372  * The availability of this functor is not dependent on the library
373  * having been installed with the \--with-glib-memory-slices-compat or
374  * \--with-glib-memory-slices-no-compat configuration option (see @ref
375  * Memory for further details of those options).
376  */
377 template <class T> class GSliceDestroy {
378  template <class U> void destroy(U& obj) {obj.~U();}
379 public:
380  void operator()(T obj) {
381  destroy(*obj);
382  g_slice_free1(sizeof(*obj), (void*)obj);
383  }
384 };
385 
386 /**
387  * @class GSliceFreeSize shared_handle.h c++-gtk-utils/shared_handle.h
388  * @brief A deleter functor for use as the second (Dealloc) template
389  * parameter of the SharedHandle, SharedLockHandle or ScopedHandle
390  * template classes, which calls glib's g_slice_free1().
391  * @ingroup handles
392  *
393  * @details This functor enables those classes to manage memory
394  * allocated with g_slice_alloc(), g_slice_alloc0() or g_slice_copy().
395  * It is an alternative to using GSliceFree where, instead of the
396  * template parameter being a pointer to a particular managed type,
397  * the size of the memory block to be freed is passed, so enabling it
398  * to be more conveniently used to free memory containing arrays of
399  * built-in types or of PODSs. Use GSliceDestroy where the memory
400  * holds a C++ object constructed in the memory by the global
401  * placement new expression.
402  *
403  * The type of the template argument for the functor is an integer
404  * type (gsize) and is the size of the block to be managed. For
405  * example:
406  *
407  * @code
408  * using namespace Cgu;
409  * SharedHandle<char*, GSliceFreeSize<10> > h(static_cast<char*>(g_slice_alloc(10)));
410  * ...
411  * @endcode
412  *
413  * The availability of this functor is not dependent on the library
414  * having been installed with the \--with-glib-memory-slices-compat or
415  * \--with-glib-memory-slices-no-compat configuration option (see @ref
416  * Memory for further details of those options).
417  */
418 template <gsize block_size> class GSliceFreeSize {
419 public:
420  void operator()(const void* obj) {
421  g_slice_free1(block_size, const_cast<void*>(obj));
422  }
423 };
424 
425 /*
426  * we could provide a functor class for
427  * g_slice_free_chain_with_offset() such as:
428  *
429  * template <class T, gsize offset> class GSliceFreeChain {
430  * public:
431  * void operator()(T obj) {
432  * g_slice_free_chain_with_offset(sizeof(*obj), (void*)obj, offset);
433  * }
434  * };
435  *
436  * However, this is not going to be particularly useful because the
437  * G_STRUCT_OFFSET macro and/or C's offsetof macro, needed to provide
438  * the value for the offset parameter, do not work for other than
439  * PODSs. g_slice_free_chain_with_offset() is intended for internal
440  * implementations and in the event of a user wanting such memory
441  * management it is best achieved by having custom new[] and delete[]
442  * member operators of the class concerned which use glib's
443  * g_slice_*() directly.
444  */
445 
446 /********************* define some typedefs for Glib ******************/
447 
448 template <class T, class Dealloc> class SharedHandle;
449 template <class T, class Dealloc> class ScopedHandle;
450 
451 /**
452  * @typedef GcharSharedHandle.
453  * @brief A handle comprising a typed instance of the SharedHandle
454  * class for gchar* arrays and strings
455  * @anchor GcharSharedHandleAnchor
456  * @ingroup handles
457  * \#include <c++-gtk-utils/shared_handle.h>
458  */
460 
461 /**
462  * @typedef GcharScopedHandle.
463  * @brief A handle comprising a typed instance of the ScopedHandle
464  * class for gchar* arrays and strings
465  * @anchor GcharScopedHandleAnchor
466  * @ingroup handles
467  * \#include <c++-gtk-utils/shared_handle.h>
468 */
470 
471 
472 /******************* now the handle class definitions *****************/
473 
474 /**
475  * @class SharedHandleError shared_handle.h c++-gtk-utils/shared_handle.h
476  * @brief This is an exception struct thrown as an alternative to
477  * deleting a managed object when internal memory allocation for
478  * SharedHandle or SharedLockHandle fails in their reset() method or
479  * in their constructor which takes a pointer.
480  * @sa SharedHandle SharedLockHandle SharedHandleAllocFail
481  * @ingroup handles
482  *
483  * This is an exception struct thrown as an alternative to deleting a
484  * managed object when SharedHandle<T>::SharedHandle(T),
485  * SharedLockHandle<T>::SharedLockHandle(T), SharedHandle<T>::reset(T)
486  * or SharedLockHandle<T>::reset(T) would otherwise throw
487  * std::bad_alloc. To make those methods do that,
488  * Cgu::SharedHandleAllocFail::leave is passed as their second
489  * argument.
490  *
491  * If the exception is thrown, the struct has a member 'obj' of type
492  * T, which is a pointer to the object or array originally passed to
493  * those methods, so the user can deal with it appropriately. This
494  * enables the result of the new expression to be passed directly as
495  * the argument to those methods without giving rise to a resource
496  * leak, as in:
497  *
498  * @code
499  * using namespace Cgu;
500  * SharedHandle<T*> s; // doesn't throw
501  * try {
502  * s.reset(new T[2], SharedHandleAllocFail::leave); // both T allocation and reset() might throw
503  * }
504  * catch (std::bad_alloc&) {
505  * ...
506  * }
507  * catch (SharedHandleError<T*>& e) {
508  * e.obj[0].do_something();
509  * e.obj[1].do_something();
510  * ...
511  * }
512  * ...
513  * @endcode
514  *
515  * As above, a catch block will need to deal with std::bad_alloc (if
516  * the call to the new expression when creating the T object fails)
517  * as well as SharedHandleError (if the call to the new expression in
518  * the reset() method fails after a valid T object has been
519  * constructed).
520  */
521 
522 template <class T> struct SharedHandleError: public std::exception {
523  T obj;
524  virtual const char* what() const throw() {return "SharedHandleError\n";}
525  SharedHandleError(T p): obj(p) {}
526 };
527 
528 /**
529  * enum Cgu::SharedHandleAllocFail::Leave
530  * The enumerator Cgu::SharedHandleAllocFail::leave is passed as the
531  * second argument of the reset() method of SharedHandle or
532  * SharedLockHandle in order to prevent the method deleting the object
533  * passed to it if reset() fails internally because of memory
534  * exhaustion.
535  * @ingroup handles
536  */
537 namespace SharedHandleAllocFail {
538  enum Leave {leave};
539 }
540 
541 template <class T, class Dealloc = StandardArrayDelete<T>> class SharedHandle {
542 
543  Dealloc deleter;
544 
545 #ifndef DOXYGEN_PARSING
546  struct RefItems {
547  unsigned int* ref_count_p;
548  T obj;
549  } ref_items;
550 #endif
551 
552  void unreference() {
553  if (!ref_items.ref_count_p) return;
554  --(*ref_items.ref_count_p);
555  if (*ref_items.ref_count_p == 0) {
556 #ifdef CGU_USE_GLIB_MEMORY_SLICES_NO_COMPAT
557  g_slice_free(unsigned int, ref_items.ref_count_p);
558 #else
559  delete ref_items.ref_count_p;
560 #endif
561  deleter(ref_items.obj);
562  }
563  }
564 
565  void reference() {
566  if (!ref_items.ref_count_p) return;
567  ++(*ref_items.ref_count_p);
568  }
569 
570 public:
571 /**
572  * Constructor taking an unmanaged object.
573  * @param ptr The object which the SharedHandle is to manage (if
574  * any).
575  * @exception std::bad_alloc This constructor will not throw if the
576  * 'ptr' argument has a NULL value (the default), otherwise it might
577  * throw std::bad_alloc if memory is exhausted and the system throws
578  * in that case. If such an exception is thrown, this constructor is
579  * exception safe (it does not leak resources), but as well as
580  * cleaning itself up this constructor will also delete the managed
581  * object passed to it to avoid a memory leak. If such automatic
582  * deletion is not wanted in that case, use the version of this
583  * constructor taking a Cgu::SharedHandleAllocFail::Leave tag argument.
584  * @note std::bad_alloc will not be thrown if the library has been
585  * installed using the \--with-glib-memory-slices-no-compat
586  * configuration option: instead glib will terminate the program if it
587  * is unable to obtain memory from the operating system.
588  */
589  explicit SharedHandle(T ptr = 0) {
590 
591  if ((ref_items.obj = ptr)) { // not NULL
592 #ifdef CGU_USE_GLIB_MEMORY_SLICES_NO_COMPAT
593  ref_items.ref_count_p = g_slice_new(unsigned int);
594  *ref_items.ref_count_p = 1;
595 #else
596  try {
597  ref_items.ref_count_p = new unsigned int(1);
598  }
599  catch (...) {
600  deleter(ptr); // if allocating the int referenced by ref_items.ref_count_p
601  // has failed then delete the object to be referenced to
602  // avoid a memory leak
603  throw;
604  }
605 #endif
606  }
607  else ref_items.ref_count_p = 0;
608  }
609 
610 /**
611  * Constructor taking an unmanaged object.
612  * @param ptr The object which the SharedHandle is to manage
613  * @param tag Passing the tag emumerator
614  * Cgu::SharedHandleAllocFail::leave causes this constructor not to
615  * delete the new managed object passed as the 'ptr' argument in the
616  * event of internal allocation in this method failing because of
617  * memory exhaustion (in that event, Cgu::SharedHandleError will be
618  * thrown).
619  * @exception Cgu::SharedHandleError This constructor might throw
620  * Cgu::SharedHandleError if memory is exhausted and the system would
621  * otherwise throw std::bad_alloc in that case. This constructor is
622  * exception safe (it does not leak resources), and if such an
623  * exception is thrown it will clean itself up, but it will not
624  * attempt to delete the new managed object passed to it. Access to
625  * the object passed to the 'ptr' argument can be obtained via the
626  * thrown Cgu::SharedHandleError object.
627  * @note 1. On systems with over-commit/lazy-commit combined with
628  * virtual memory (swap), it is rarely useful to check for memory
629  * exhaustion, so in those cases this version of the constructor will
630  * not be useful.
631  * @note 2. If the library has been installed using the
632  * \--with-glib-memory-slices-no-compat configuration option this
633  * version of the constructor will also not be useful: instead glib
634  * will terminate the program if it is unable to obtain memory from
635  * the operating system.
636  */
638 
639  if ((ref_items.obj = ptr)) { // not NULL
640 #ifdef CGU_USE_GLIB_MEMORY_SLICES_NO_COMPAT
641  ref_items.ref_count_p = g_slice_new(unsigned int);
642  *ref_items.ref_count_p = 1;
643 #else
644  try {
645  ref_items.ref_count_p = new unsigned int(1);
646  }
647  catch (std::bad_alloc&) { // as we are not rethrowing, make NPTL friendly
648  throw SharedHandleError<T>(ptr);
649  }
650 #endif
651  }
652  else ref_items.ref_count_p = 0;
653  }
654 
655 /**
656  * Causes the SharedHandle to cease to manage its managed object (if
657  * any), deleting it if this is the last SharedHandle object managing
658  * it. If the argument passed is not NULL, the SharedHandle object
659  * will manage the new object passed (which must not be managed by any
660  * other SharedHandle object). This method is exception safe, but see
661  * the comments below on std::bad_alloc.
662  * @param ptr NULL (the default), or a new unmanaged object to manage.
663  * @exception std::bad_alloc This method will not throw if the 'ptr'
664  * argument has a NULL value (the default) and the destructor of a
665  * managed object does not throw, otherwise it might throw
666  * std::bad_alloc if memory is exhausted and the system throws in that
667  * case. Note that if such an exception is thrown then this method
668  * will do nothing (it is strongly exception safe and will continue to
669  * manage the object it was managing prior to the call), except that
670  * it will delete the new managed object passed to it to avoid a
671  * memory leak. If such automatic deletion in the event of such an
672  * exception is not wanted, use the reset() method taking a
673  * Cgu::SharedHandleAllocFail::Leave tag type as its second argument.
674  * @note std::bad_alloc will not be thrown if the library has been
675  * installed using the \--with-glib-memory-slices-no-compat
676  * configuration option: instead glib will terminate the program if it
677  * is unable to obtain memory from the operating system.
678  */
679  void reset(T ptr = 0) {
680  SharedHandle tmp(ptr);
681  std::swap(ref_items, tmp.ref_items);
682  }
683 
684 /**
685  * Causes the SharedHandle to cease to manage its managed object (if
686  * any), deleting it if this is the last SharedHandle object managing
687  * it. The SharedHandle object will manage the new object passed
688  * (which must not be managed by any other SharedHandle object). This
689  * method is exception safe, but see the comments below on
690  * Cgu::SharedHandleError.
691  * @param ptr A new unmanaged object to manage (if no new object is to
692  * be managed, use the version of reset() taking a default value of
693  * NULL).
694  * @param tag Passing the tag emumerator
695  * Cgu::SharedHandleAllocFail::leave causes this method not to delete
696  * the new managed object passed as the 'ptr' argument in the event of
697  * internal allocation in this method failing because of memory
698  * exhaustion (in that event, Cgu::SharedHandleError will be thrown).
699  * @exception Cgu::SharedHandleError This method might throw
700  * Cgu::SharedHandleError if memory is exhausted and the system would
701  * otherwise throw std::bad_alloc in that case. Note that if such an
702  * exception is thrown then this method will do nothing (it is
703  * strongly exception safe and will continue to manage the object it
704  * was managing prior to the call), and it will not attempt to delete
705  * the new managed object passed to it. Access to the object passed
706  * to the 'ptr' argument can be obtained via the thrown
707  * Cgu::SharedHandleError object.
708  * @note 1. On systems with over-commit/lazy-commit combined with
709  * virtual memory (swap), it is rarely useful to check for memory
710  * exhaustion, so in those cases this version of the reset() method
711  * will not be useful.
712  * @note 2. If the library has been installed using the
713  * \--with-glib-memory-slices-no-compat configuration option this
714  * version of the reset() method will also not be useful: instead glib
715  * will terminate the program if it is unable to obtain memory from
716  * the operating system.
717  */
719  SharedHandle tmp(ptr, tag);
720  std::swap(ref_items, tmp.ref_items);
721  }
722 
723  /**
724  * The copy constructor does not throw.
725  * @param sh_hand The handle to be copied.
726  */
727  SharedHandle(const SharedHandle& sh_hand) {
728  ref_items = sh_hand.ref_items;
729  reference();
730  }
731 
732  /**
733  * The move constructor does not throw. It has move semantics.
734  * @param sh_hand The handle to be moved.
735  */
737  ref_items = sh_hand.ref_items;
738  sh_hand.ref_items.ref_count_p = 0;
739  sh_hand.ref_items.obj = 0;
740  }
741 
742  /**
743  * This method (and so copy or move assignment) does not throw unless
744  * the destructor of a managed object throws.
745  * @param sh_hand the assignor.
746  * @return The SharedHandle object after assignment.
747  */
748  // having a value type as the argument, rather than reference to const
749  // and then initialising a tmp object, gives the compiler more scope
750  // for optimisation, and also caters for r-values without a separate
751  // overload
753  std::swap(ref_items, sh_hand.ref_items);
754  return *this;
755  }
756 
757  /**
758  * This method does not throw.
759  * @return A pointer to the handled object (or NULL if none is
760  * handled).
761  */
762  T get() const {return ref_items.obj;}
763 
764  /**
765  * This method does not throw.
766  * @return A pointer to the handled object (or NULL if none is
767  * handled).
768  */
769  operator T() const {return ref_items.obj;}
770 
771  /**
772  * This method does not throw.
773  * @return The number of SharedHandle objects referencing the managed
774  * object (or 0 if none is managed by this SharedHandle).
775  */
776  unsigned int get_refcount() const {return (ref_items.ref_count_p) ? *ref_items.ref_count_p : 0;}
777 
778  /**
779  * The destructor does not throw unless the destructor of a handled
780  * object throws - that should never happen.
781  */
782  ~SharedHandle() {unreference();}
783 };
784 
785 /**
786  * @class ScopedHandle shared_handle.h c++-gtk-utils/shared_handle.h
787  * @brief This is a generic scoped class for managing the lifetime of objects
788  * allocated on freestore.
789  * @ingroup handles
790  * @sa SharedHandle SharedLockHandle SharedHandleError
791  * @sa StandardArrayDelete CFree GFree GerrorFree GSliceFree GSliceFreeSize GSliceDestroy
792  *
793  * This class deletes its object as soon as it goes out of scope. It
794  * can be viewed as a SharedHandle which cannot be copy assigned to or
795  * used as the argument to a copy constructor and therefore which
796  * cannot have a reference count of more than 1.
797  *
798  * ScopedHandle objects can be instantiated for pointers to constant
799  * objects (such as ScopedHandle<const char*>), provided the deleter
800  * functor will take such pointers.
801  *
802  * This library provides StandardArrayDelete, CFree, GFree,
803  * GerrorFree, GSliceFree, GSliceFreeSize and GSliceDestroy deleter
804  * functors, which can be used as the second template parameter of the
805  * ScopedHandle class. StandardArrayDelete is the default, and some
806  * typedef'ed instances of ScopedHandle for gchar (with the GFree
807  * deleter) and for GError (with the GerrorFree deleter) are provided:
808  * @ref GcharScopedHandleAnchor "GcharScopedHandle" and @ref
809  * GerrorScopedHandleAnchor "GerrorScopedHandle")
810  *
811  * @b Comparison @b with @b std::unique_ptr
812  *
813  * Although the semantics of std::unique_ptr in C++11 are not
814  * particularly suited to managing C objects with accessor functions
815  * (such as in glib), most of the things that can be done by this
816  * class can be done by using std::unique_ptr with a specialised
817  * deleter. However, this class is retained in the c++-gtk-utils
818  * library not only to retain compatibility with series 1.2 of the
819  * library, but also because the Cgu::ScopedHandle class takes its
820  * deleter as a template parameter, which means that typedefs can be
821  * used to enable handles for particular deleters to be easily created
822  * (and as mentioned, this library provides a number of pre-formed
823  * deleter functors and typedefs for them). With std::unique_ptr,
824  * custom deleters must be passed to the unique_ptr constructor on
825  * every occasion a unique_ptr is constructed to manage a new object
826  * (and they cannot be templated as a typedef).
827  *
828  * From version 2.2.2, this class has a move constructor and move
829  * assignment operator. Prior to that, it could not be moved from or
830  * to.
831  */
832 
833 template <class T, class Dealloc = StandardArrayDelete<T>> class ScopedHandle {
834  Dealloc deleter;
835  T obj;
836 public:
837 /**
838  * This class cannot be copied. The copy constructor is deleted.
839  */
840  ScopedHandle(const ScopedHandle&) = delete;
841 
842 /**
843  * This class cannot be copied. The copy assignment operator is
844  * deleted.
845  */
846  ScopedHandle& operator=(const ScopedHandle&) = delete;
847 
848 /**
849  * The move constructor does not throw.
850  * @param sc_hand The handle to be moved.
851  *
852  * Since 2.0.19/2.2.2
853  */
855  obj = sc_hand.obj;
856  sc_hand.obj = 0;
857  }
858 
859 /**
860  * The move assignment operator. It will delete the object managed
861  * prior to the move, if any. It does not throw unless the destructor
862  * of that object throws.
863  * @param sc_hand The handle to be moved.
864  * @return The ScopedHandle object after move assignment.
865  *
866  * Since 2.0.19/2.2.2
867  */
869  reset(sc_hand.release());
870  return *this;
871  }
872 
873 /**
874  * This constructor does not throw.
875  * @param ptr The object which the ScopedHandle is to manage (if
876  * any).
877  *
878  * ScopedHandle objects can be instantiated for pointers to constant
879  * objects (such as SharedHandle<const char*>), provided the deleter
880  * functor will take such pointers.
881  */
882  explicit ScopedHandle(T ptr = 0): obj(ptr) {}
883 
884 /**
885  * Causes the ScopedHandle to delete its managed object (if any), and
886  * if the argument passed is not NULL, the ScopedHandle object will
887  * manage the new object passed (which must not be managed by any
888  * other ScopedHandle object). This method does not throw (assuming
889  * the destructor of a managed object does not throw).
890  * @param ptr NULL (the default), or a new unmanaged object to manage.
891  */
892  void reset(T ptr = 0) {
893  std::swap(obj, ptr);
894  if (ptr) deleter(ptr); // ptr now points to the original managed object
895  }
896 
897 /**
898  * Causes the ScopedHandle to cease to manage the handled object, but
899  * does not delete that object. This method does not throw.
900  * @return A pointer to the previously handled object (or NULL if none
901  * was handled).
902  */
903  T release() {T tmp = obj; obj = 0; return tmp;}
904 
905 /**
906  * This method does not throw.
907  * @return A pointer to the handled object (or NULL if none is
908  * handled).
909  */
910  T get() const {return obj;}
911 
912 /**
913  * This method does not throw.
914  * @return A pointer to the handled object (or NULL if none is
915  * handled).
916  */
917  operator T() const {return obj;}
918 
919 /**
920  * The destructor does not throw unless the destructor of a handled
921  * object throws - that should never happen.
922  */
923  ~ScopedHandle() {if (obj) deleter(obj);}
924 };
925 
926 
927 /**
928  * @class SharedLockHandle shared_handle.h c++-gtk-utils/shared_handle.h
929  * @brief This is a generic class for managing the lifetime of objects
930  * allocated on freestore, with a thread safe reference count..
931  * @ingroup handles
932  * @sa SharedHandle ScopedHandle SharedHandleError
933  * @sa StandardArrayDelete CFree GFree GerrorFree GSliceFree GSliceFreeSize GSliceDestroy
934  *
935  * Class SharedLockHandle is a version of the SharedHandle class which
936  * includes synchronization so that it can handle objects accessed in
937  * multiple threads (although the word Lock is in the title, by
938  * default it uses glib atomic functions to access the reference count
939  * rather than a mutex, so the overhead should be very small). Note
940  * that only the reference count is protected, so this is thread safe
941  * in the sense in which a raw pointer is thread safe. A shared
942  * handle accessed in one thread referencing a particular object is
943  * thread safe as against another shared handle accessing the same
944  * object in a different thread. It is thus suitable for use in
945  * different standard C++ containers which exist in different threads
946  * but which contain shared objects by reference. But:
947  *
948  * 1. If the referenced object is to be modified in one thread and
949  * read or modified in another thread an appropriate mutex for the
950  * referenced object is required (unless that referenced object
951  * does its own locking).
952  * 2. If the same instance of shared handle is to be modified in one
953  * thread (by assigning to the handle so that it references a
954  * different object, or by moving from it), and copied (assigned
955  * from or used as the argument of a copy constructor), accessed,
956  * destroyed or modified in another thread, a mutex for that
957  * instance of shared handle is required.
958  * 3. Objects referenced by shared handles which are objects for
959  * which POSIX provides no guarantees (in the main, those which
960  * are not built-in types), such as strings and similar
961  * containers, may not support concurrent reads in different
962  * threads. That depends on the library implementation concerned.
963  * If that is the case, a mutex for the referenced object will
964  * also be required when reading any given instance of such an
965  * object in more than one thread by dereferencing any shared
966  * handles referencing it (and indeed, when not using shared
967  * handles at all).
968  *
969  * SharedLockHandle objects can be instantiated for pointers to
970  * constant objects (such as SharedLockHandle<const char*>), provided
971  * the deleter functor will take such pointers.
972  *
973  * This library provides StandardArrayDelete, CFree, GFree,
974  * GerrorFree, GSliceFree, GSliceFreeSize and GSliceDestroy deleter
975  * functors, which can be used as the second template parameter of the
976  * SharedLockHandle class. StandardArrayDelete is the default.
977  *
978  * As mentioned, by default glib atomic functions are used to provide
979  * thread-safe manipulation of the reference count. However, the
980  * symbol CGU_SHARED_LOCK_HANDLE_USE_MUTEX can be defined so that the
981  * library uses mutexes instead, which might be useful for some
982  * debugging purposes. Note that if CGU_SHARED_LOCK_HANDLE_USE_MUTEX
983  * is to be defined, this is best done by textually amending the
984  * shared_handle.h header file before the library is compiled. This
985  * will ensure that everything in the program and the library which
986  * includes the shared_handle.h header is guaranteed to see the same
987  * definitions so that the C++ standard's one-definition-rule is
988  * complied with.
989  *
990  * @b Comparison @b with @b std::shared_ptr
991  *
992  * Although the semantics of std::shared_ptr in C++11 are not
993  * particularly suited to managing either arrays or C objects with
994  * accessor functions (such as in glib), most of the things that can
995  * be done by this class can be done by using std::shared_ptr with a
996  * specialised deleter. However, this class is retained in the
997  * c++-gtk-utils library not only to retain compatibility with series
998  * 1.2 of the library, but also to cater for some cases not met (or
999  * not so easily met) by std::shared_ptr:
1000  *
1001  * 1. The Cgu::SharedLockHandle class takes its deleter as a template
1002  * parameter, which means that typedefs can be used to enable
1003  * handles for particular deleters to be easily created (and as
1004  * mentioned, this library provides a number of pre-formed deleter
1005  * functors and typedefs for them). With std::shared_ptr, custom
1006  * deleters must be passed to the shared_ptr constructor on every
1007  * occasion a shared_ptr is constructed to manage a new object (and
1008  * they cannot be templated as a typedef).
1009  * 2. Glib memory slices provide an efficient small object allocator
1010  * (they are likely to be significantly more efficient than global
1011  * operator new()/new[](), which generally hand off to malloc(),
1012  * and whilst malloc() is good for large block allocations it is
1013  * generally poor as a small object allocator). Internal
1014  * Cgu::SharedLockHandle allocation using glib memory slices can be
1015  * achieved by compiling the library with the
1016  * \--with-glib-memory-slices-no-compat configuration option.
1017  * 3. If glib memory slices are not used (which do not throw),
1018  * constructing a shared pointer for a new managed object (or
1019  * calling reset() for a new managed object) might throw if
1020  * internal allocation fails. Although by default the
1021  * Cgu::SharedLockHandle implementation will delete the new managed
1022  * object in such a case, it also provides an alternative
1023  * constructor and reset() method which instead enable the new
1024  * object to be accessed via the thrown exception object so that
1025  * user code can decide what to do; std::shared_ptr deletes the new
1026  * object in every case.
1027  * 4. A user can explicitly state whether the shared handle object is
1028  * to have atomic increment and decrement-and-test with respect to
1029  * the reference count so that the reference count is thread safe
1030  * ('no' in the case of Cgu::SharedHandle, and 'yes' in the case of
1031  * Cgu::SharedLockHandle). Using atomic functions is unnecessary
1032  * if the managed object concerned is only addressed in one thread
1033  * (and might cause unwanted cache flushing in certain
1034  * circumstances). std::shared_ptr will generally always use
1035  * atomic functions with respect to its reference count in a
1036  * multi-threaded program.
1037  *
1038  * In favour of std::shared_ptr, it has an associated std::weak_ptr
1039  * class, which Cgu::SharedLockHandle does not (there is a
1040  * Cgu::GobjWeakHandle class, but that is cognate with Cgu::GobjHandle
1041  * and is only usable with GObjects). In addition shared_ptr objects
1042  * have some atomic store, load and exchange functions provided for
1043  * them which enable concurrent modifications of the same instance of
1044  * shared_ptr in different threads to have defined results.
1045  *
1046  * If the library is compiled with the
1047  * \--with-glib-memory-slices-no-compat configuration option, as
1048  * mentioned Cgu::SharedLockHandle constructs its reference counting
1049  * internals using glib memory slices. Although it is safe in a
1050  * multi-threaded program if glib < 2.32 is installed to construct a
1051  * static SharedLockHandle object in global namespace (that is, prior
1052  * to g_thread_init() being called) by means of the default
1053  * constructor and/or a pointer argument of NULL, it is not safe if
1054  * constructed with a non-NULL pointer value. If glib >= 2.32 is
1055  * installed, global objects with memory slices are safe in all
1056  * circumstances. (Having said that, it would be highly unusual to
1057  * have global SharedLockHandle objects.)
1058  */
1059 
1060 template <class T, class Dealloc = StandardArrayDelete<T>> class SharedLockHandle {
1061 
1062  Dealloc deleter;
1063 
1064 #ifndef DOXYGEN_PARSING
1065  struct RefItems {
1066 #ifdef CGU_SHARED_LOCK_HANDLE_USE_MUTEX
1067  Thread::Mutex* mutex_p;
1068  unsigned int* ref_count_p;
1069 #else
1070  gint* ref_count_p;
1071 #endif
1072  T obj;
1073  } ref_items;
1074 #endif
1075 
1076  // SharedLockHandle<T, Dealloc>::unreference() does not throw exceptions
1077  // because Thread::Mutex::~Mutex(), Thread::Mutex::lock() and Thread::Mutex::unlock()
1078  // do not throw
1079  void unreference() {
1080  // we can (and should) check whether ref_items.ref_count_p is NULL without
1081  // a lock, because that member is specific to this SharedLockHandle object.
1082  // Only the integer pointed to by it is shared amongst SharedLockHandle
1083  // objects and requires locking
1084  if (!ref_items.ref_count_p) return;
1085 #ifdef CGU_SHARED_LOCK_HANDLE_USE_MUTEX
1086  ref_items.mutex_p->lock();
1087  --(*ref_items.ref_count_p);
1088  if (*ref_items.ref_count_p == 0) {
1089 # ifdef CGU_USE_GLIB_MEMORY_SLICES_NO_COMPAT
1090  g_slice_free(unsigned int, ref_items.ref_count_p);
1091 # else
1092  delete ref_items.ref_count_p;
1093 # endif
1094  ref_items.mutex_p->unlock();
1095  delete ref_items.mutex_p;
1096  deleter(ref_items.obj);
1097  }
1098  else ref_items.mutex_p->unlock();
1099 #else
1100  if (g_atomic_int_dec_and_test(ref_items.ref_count_p)) {
1101 # ifdef CGU_USE_GLIB_MEMORY_SLICES_NO_COMPAT
1102  g_slice_free(gint, ref_items.ref_count_p);
1103 # else
1104  delete ref_items.ref_count_p;
1105 # endif
1106  deleter(ref_items.obj);
1107  }
1108 #endif
1109  }
1110 
1111  // SharedLockHandle<T, Dealloc>::reference() does not throw exceptions because
1112  // Thread::Mutex::Lock::Lock() and Thread::Mutex::Lock::~Lock() do not throw
1113  void reference() {
1114  // we can (and should) check whether ref_items.ref_count_p is NULL without
1115  // a lock, because that member is specific to this SharedLockHandle object.
1116  // Only the integer pointed to by it is shared amongst SharedLockHandle
1117  // objects and requires locking
1118  if (!ref_items.ref_count_p) return;
1119 #ifdef CGU_SHARED_LOCK_HANDLE_USE_MUTEX
1120  Thread::Mutex::Lock lock(*ref_items.mutex_p);
1121  ++(*ref_items.ref_count_p);
1122 #else
1123  g_atomic_int_inc(ref_items.ref_count_p);
1124 #endif
1125  }
1126 
1127 public:
1128 /**
1129  * Constructor taking an unmanaged object.
1130  * @param ptr The object which the SharedLockHandle is to manage (if
1131  * any).
1132  * @exception std::bad_alloc This constructor will not throw if the
1133  * 'ptr' argument has a NULL value (the default), otherwise it might
1134  * throw std::bad_alloc if memory is exhausted and the system throws
1135  * in that case. If such an exception is thrown, this constructor is
1136  * exception safe (it does not leak resources), but as well as
1137  * cleaning itself up this constructor will also delete the managed
1138  * object passed to it to avoid a memory leak. If such automatic
1139  * deletion is not wanted in that case, use the version of this
1140  * constructor taking a Cgu::SharedHandleAllocFail::Leave tag
1141  * argument.
1142  * @note 1. std::bad_alloc will not be thrown if the library has been
1143  * installed using the \--with-glib-memory-slices-no-compat
1144  * configuration option: instead glib will terminate the program if it
1145  * is unable to obtain memory from the operating system.
1146  * @note 2. By default, glib atomic functions are used to provide
1147  * thread-safe manipulation of the reference count. However, the
1148  * header file shared_handle.h can be textually amended before the
1149  * library is compiled to define the symbol
1150  * CGU_SHARED_LOCK_HANDLE_USE_MUTEX so as to use mutexes instead,
1151  * which might be useful for some debugging purposes. Were that to be
1152  * done, Cgu::Thread::MutexError might be thrown by this constructor
1153  * if initialization of the mutex fails.
1154  */
1155  explicit SharedLockHandle(T ptr = 0) {
1156 
1157  if ((ref_items.obj = ptr)) { // not NULL
1158 #ifdef CGU_SHARED_LOCK_HANDLE_USE_MUTEX
1159  try {
1160  ref_items.mutex_p = new Thread::Mutex;
1161  }
1162  catch (...) {
1163  deleter(ptr); // if allocating the object referenced by ref_items.mutex_p
1164  // has failed then delete the object to be referenced to
1165  // avoid a memory leak
1166  throw;
1167  }
1168 # ifdef CGU_USE_GLIB_MEMORY_SLICES_NO_COMPAT
1169  ref_items.ref_count_p = g_slice_new(unsigned int);
1170  *ref_items.ref_count_p = 1;
1171 # else
1172  try {
1173  ref_items.ref_count_p = new unsigned int(1);
1174  }
1175  catch (...) {
1176  delete ref_items.mutex_p;
1177  deleter(ptr);
1178  throw;
1179  }
1180 # endif
1181 #else
1182 # ifdef CGU_USE_GLIB_MEMORY_SLICES_NO_COMPAT
1183  ref_items.ref_count_p = g_slice_new(gint);
1184  *ref_items.ref_count_p = 1;
1185 # else
1186  try {
1187  ref_items.ref_count_p = new gint(1);
1188  }
1189  catch (...) {
1190  deleter(ptr); // if allocating the int referenced by ref_items.ref_count_p
1191  // has failed then delete the object to be referenced to
1192  // avoid a memory leak
1193  throw;
1194  }
1195 # endif
1196 #endif
1197  }
1198  else {
1199 #ifdef CGU_SHARED_LOCK_HANDLE_USE_MUTEX
1200  ref_items.mutex_p = 0; // make sure the value is valid as we may assign it
1201 #endif
1202  ref_items.ref_count_p = 0;
1203  }
1204  }
1205 
1206  /**
1207  * Constructor taking an unmanaged object.
1208  * @param ptr The object which the SharedLockHandle is to manage.
1209  * @param tag Passing the tag emumerator
1210  * Cgu::SharedHandleAllocFail::leave causes this constructor not to
1211  * delete the new managed object passed as the 'ptr' argument in the
1212  * event of internal allocation in this method failing because of
1213  * memory exhaustion (in that event, Cgu::SharedHandleError will be
1214  * thrown).
1215  * @exception Cgu::SharedHandleError This constructor might throw
1216  * Cgu::SharedHandleError if memory is exhausted and the system would
1217  * otherwise throw std::bad_alloc in that case. This constructor is
1218  * exception safe (it does not leak resources), and if such an
1219  * exception is thrown it will clean itself up, but it will not
1220  * attempt to delete the new managed object passed to it. Access to
1221  * the object passed to the 'ptr' argument can be obtained via the
1222  * thrown Cgu::SharedHandleError object.
1223  * @note 1. On systems with over-commit/lazy-commit combined with
1224  * virtual memory (swap), it is rarely useful to check for memory
1225  * exhaustion, so in those cases this version of the constructor will
1226  * not be useful.
1227  * @note 2. If the library has been installed using the
1228  * \--with-glib-memory-slices-no-compat configuration option this
1229  * version of the constructor will also not be useful: instead glib
1230  * will terminate the program if it is unable to obtain memory from
1231  * the operating system.
1232  * @note 3. By default, glib atomic functions are used to provide
1233  * thread-safe manipulation of the reference count. However, the
1234  * header file shared_handle.h can be textually amended before the
1235  * library is compiled to define the symbol
1236  * CGU_SHARED_LOCK_HANDLE_USE_MUTEX so as to use mutexes instead,
1237  * which might be useful for some debugging purposes. Were that to be
1238  * done, Cgu::SharedHandleError might be thrown by this constructor if
1239  * initialization of the mutex fails (even if the
1240  * \--with-glib-memory-slices-no-compat configuration option is
1241  * chosen).
1242  */
1244 
1245  if ((ref_items.obj = ptr)) { // not NULL
1246 #ifdef CGU_SHARED_LOCK_HANDLE_USE_MUTEX
1247  try {
1248  ref_items.mutex_p = new Thread::Mutex;
1249  }
1250  catch (std::bad_alloc&) { // as we are not rethrowing, make NPTL friendly
1251  throw SharedHandleError<T>(ptr);
1252  }
1253  catch (Thread::MutexError&) { // as we are not rethrowing, make NPTL friendly
1254  throw SharedHandleError<T>(ptr);
1255  }
1256 # ifdef CGU_USE_GLIB_MEMORY_SLICES_NO_COMPAT
1257  ref_items.ref_count_p = g_slice_new(unsigned int);
1258  *ref_items.ref_count_p = 1;
1259 # else
1260  try {
1261  ref_items.ref_count_p = new unsigned int(1);
1262  }
1263  catch (std::bad_alloc&) {
1264  delete ref_items.mutex_p;
1265  throw SharedHandleError<T>(ptr);
1266  }
1267 # endif
1268 #else
1269 # ifdef CGU_USE_GLIB_MEMORY_SLICES_NO_COMPAT
1270  ref_items.ref_count_p = g_slice_new(gint);
1271  *ref_items.ref_count_p = 1;
1272 # else
1273  try {
1274  ref_items.ref_count_p = new gint(1);
1275  }
1276  catch (std::bad_alloc&) { // as we are not rethrowing, make NPTL friendly
1277  throw SharedHandleError<T>(ptr);
1278  }
1279 # endif
1280 #endif
1281  }
1282  else {
1283 #ifdef CGU_SHARED_LOCK_HANDLE_USE_MUTEX
1284  ref_items.mutex_p = 0; // make sure the value is valid as we may assign it
1285 #endif
1286  ref_items.ref_count_p = 0;
1287  }
1288  }
1289 
1290 /**
1291  * Causes the SharedLockHandle to cease to manage its managed object
1292  * (if any), deleting it if this is the last ShareLockHandle object
1293  * managing it. If the argument passed is not NULL, the
1294  * SharedLockHandle object will manage the new object passed (which
1295  * must not be managed by any other SharedLockHandle object).
1296  * @param ptr NULL (the default), or a new unmanaged object to manage.
1297  * @exception std::bad_alloc This method will not throw if the 'ptr'
1298  * argument has a NULL value (the default) and the destructor of a
1299  * managed object does not throw, otherwise it might throw
1300  * std::bad_alloc if memory is exhausted and the system throws in that
1301  * case. Note that if such an exception is thrown then this method
1302  * will do nothing (it is strongly exception safe and will continue to
1303  * manage the object it was managing prior to the call), except that
1304  * it will delete the new managed object passed to it to avoid a
1305  * memory leak. If such automatic deletion in the event of such an
1306  * exception is not wanted, use the reset() method taking a
1307  * Cgu::SharedHandleAllocFail::Leave tag type as its second argument.
1308  * @note 1. std::bad_alloc will not be thrown if the library has been
1309  * installed using the \--with-glib-memory-slices-no-compat
1310  * configuration option: instead glib will terminate the program if it
1311  * is unable to obtain memory from the operating system.
1312  * @note 2. By default, glib atomic functions are used to provide
1313  * thread-safe manipulation of the reference count. However, the
1314  * header file shared_handle.h can be textually amended before the
1315  * library is compiled to define the symbol
1316  * CGU_SHARED_LOCK_HANDLE_USE_MUTEX so as to use mutexes instead,
1317  * which might be useful for some debugging purposes. Were that to be
1318  * done, Cgu::Thread::MutexError might be thrown by this method if
1319  * initialization of the mutex fails.
1320  * @note 3. A SharedLockHandle object protects its reference count but
1321  * not the managed object or its other internals. The reset() method
1322  * should not be called by one thread in respect of a particular
1323  * SharedLockHandle object while another thread may be operating on,
1324  * copying or dereferencing the same instance of SharedLockHandle. It
1325  * is thread-safe as against another instance of SharedLockHandle
1326  * managing the same object.
1327  */
1328  void reset(T ptr = 0) {
1329  SharedLockHandle tmp(ptr);
1330  std::swap(ref_items, tmp.ref_items);
1331  }
1332 
1333 /**
1334  * Causes the SharedLockHandle to cease to manage its managed object
1335  * (if any), deleting it if this is the last ShareLockHandle object
1336  * managing it. The SharedLockHandle object will manage the new
1337  * object passed (which must not be managed by any other
1338  * SharedLockHandle object). This method is exception safe, but see
1339  * the comments below on Cgu::SharedHandleError.
1340  * @param ptr A new unmanaged object to manage (if no new object is to
1341  * be managed, use the version of reset() taking a default value of
1342  * NULL).
1343  * @param tag Passing the tag emumerator
1344  * Cgu::SharedHandleAllocFail::leave causes this method not to delete
1345  * the new managed object passed as the 'ptr' argument in the event of
1346  * internal allocation in this method failing because of memory
1347  * exhaustion (in that event, Cgu::SharedHandleError will be thrown).
1348  * @exception Cgu::SharedHandleError This method might throw
1349  * Cgu::SharedHandleError if memory is exhausted and the system would
1350  * otherwise throw std::bad_alloc in that case. Note that if such an
1351  * exception is thrown then this method will do nothing (it is
1352  * strongly exception safe and will continue to manage the object it
1353  * was managing prior to the call), and it will not attempt to delete
1354  * the new managed object passed to it (if any). Access to the object
1355  * passed to the 'ptr' argument can be obtained via the thrown
1356  * Cgu::SharedHandleError object.
1357  * @note 1. A SharedLockHandle object protects its reference count but
1358  * not the managed object or its other internals. The reset() method
1359  * should not be called by one thread in respect of a particular
1360  * SharedLockHandle object while another thread may be operating on,
1361  * copying or dereferencing the same instance of SharedLockHandle. It
1362  * is thread-safe as against another instance of SharedLockHandle
1363  * managing the same object.
1364  * @note 2. On systems with over-commit/lazy-commit combined with
1365  * virtual memory (swap), it is rarely useful to check for memory
1366  * exhaustion, so in those cases this version of the reset() method
1367  * will not be useful.
1368  * @note 3. If the library has been installed using the
1369  * \--with-glib-memory-slices-no-compat configuration option this
1370  * version of the reset() method will also not be useful: instead glib
1371  * will terminate the program if it is unable to obtain memory from
1372  * the operating system.
1373  * @note 4. By default, glib atomic functions are used to provide
1374  * thread-safe manipulation of the reference count. However, the
1375  * header file shared_handle.h can be textually amended before the
1376  * library is compiled to define the symbol
1377  * CGU_SHARED_LOCK_HANDLE_USE_MUTEX so as to use mutexes instead,
1378  * which might be useful for some debugging purposes. Were that to be
1379  * done, Cgu::SharedHandleError might be thrown by this method if
1380  * initialization of the mutex fails (even if the
1381  * \--with-glib-memory-slices-no-compat configuration option is
1382  * chosen).
1383  */
1385  SharedLockHandle tmp(ptr, tag);
1386  std::swap(ref_items, tmp.ref_items);
1387  }
1388 
1389  /**
1390  * The copy constructor does not throw.
1391  * @param sh_hand The handle to be copied.
1392  */
1394  ref_items = sh_hand.ref_items;
1395  reference();
1396  }
1397 
1398  /**
1399  * The move constructor does not throw. It has move semantics.
1400  * @param sh_hand The handle to be moved.
1401  */
1403  ref_items = sh_hand.ref_items;
1404 #ifdef CGU_SHARED_LOCK_HANDLE_USE_MUTEX
1405  sh_hand.ref_items.mutex_p = 0; // make sure the value is valid as we may assign it
1406 #endif
1407  sh_hand.ref_items.ref_count_p = 0;
1408  sh_hand.ref_items.obj = 0;
1409  }
1410 
1411  /**
1412  * This method (and so copy or move assignment) does not throw unless
1413  * the destructor of a managed object throws.
1414  * @param sh_hand the assignor.
1415  * @return The SharedLockHandle object after assignment.
1416  */
1417  // having a value type as the argument, rather than reference to const
1418  // and then initialising a tmp object, gives the compiler more scope
1419  // for optimisation
1421  std::swap(ref_items, sh_hand.ref_items);
1422  return *this;
1423  }
1424 
1425  /**
1426  * This method does not throw.
1427  * @return A pointer to the handled object (or NULL if none is
1428  * handled).
1429  */
1430  T get() const {return ref_items.obj;}
1431 
1432  /**
1433  * This method does not throw.
1434  * @return A pointer to the handled object (or NULL if none is
1435  * handled).
1436  */
1437  operator T() const {return ref_items.obj;}
1438 
1439  /**
1440  * This method does not throw.
1441  * @return The number of SharedLockHandle objects referencing the
1442  * managed object (or 0 if none is managed by this SharedLockHandle).
1443  * @note The return value may not be valid if another thread has
1444  * changed the reference count before the value returned by this
1445  * method is acted on. It is provided as a utility, but may not be
1446  * meaningful, depending on the intended usage.
1447  */
1448  unsigned int get_refcount() const {
1449  if (!ref_items.ref_count_p) return 0;
1450 #ifdef CGU_SHARED_LOCK_HANDLE_USE_MUTEX
1451  Thread::Mutex::Lock lock(*ref_items.mutex_p);
1452  return *ref_items.ref_count_p;
1453 #else
1454  return g_atomic_int_get(ref_items.ref_count_p);
1455 #endif
1456  }
1457 
1458  /**
1459  * The destructor does not throw unless the destructor of a handled
1460  * object throws - that should never happen.
1461  */
1462  ~SharedLockHandle() {unreference();}
1463 };
1464 
1465 #if defined(CGU_USE_SMART_PTR_COMPARISON) || defined(DOXYGEN_PARSING)
1466 
1467 // we can use built-in operator == when comparing pointers referencing
1468 // different objects of the same type
1469 /**
1470  * @ingroup handles
1471  *
1472  * This comparison operator does not throw. It compares the addresses
1473  * of the managed objects.
1474  *
1475  * Since 2.0.0-rc2
1476  */
1477 template <class T, class Dealloc>
1479  return (s1.get() == s2.get());
1480 }
1481 
1482 /**
1483  * @ingroup handles
1484  *
1485  * This comparison operator does not throw. It compares the addresses
1486  * of the managed objects.
1487  *
1488  * Since 2.0.0-rc2
1489  */
1490 template <class T, class Dealloc>
1492  return !(s1 == s2);
1493 }
1494 
1495 // we must use std::less rather than the < built-in operator for
1496 // pointers to objects not within the same array or object: "For
1497 // templates greater, less, greater_equal, and less_equal, the
1498 // specializations for any pointer type yield a total order, even if
1499 // the built-in operators <, >, <=, >= do not." (para 20.3.3/8).
1500 /**
1501  * @ingroup handles
1502  *
1503  * This comparison operator does not throw. It compares the addresses
1504  * of the managed objects.
1505  *
1506  * Since 2.0.0-rc2
1507  */
1508 template <class T, class Dealloc>
1509 bool operator<(const SharedHandle<T, Dealloc>& s1, const SharedHandle<T, Dealloc>& s2) {
1510  return std::less<T>()(s1.get(), s2.get());
1511 }
1512 
1513 /**
1514  * @ingroup handles
1515  *
1516  * This comparison operator does not throw. It compares the addresses
1517  * of the managed objects.
1518  *
1519  * Since 2.0.0-rc2
1520  */
1521 template <class T, class Dealloc>
1523  return (s1.get() == s2.get());
1524 }
1525 
1526 /**
1527  * @ingroup handles
1528  *
1529  * This comparison operator does not throw. It compares the addresses
1530  * of the managed objects.
1531  *
1532  * Since 2.0.0-rc2
1533  */
1534 template <class T, class Dealloc>
1536  return !(s1 == s2);
1537 }
1538 
1539 /**
1540  * @ingroup handles
1541  *
1542  * This comparison operator does not throw. It compares the addresses
1543  * of the managed objects.
1544  *
1545  * Since 2.0.0-rc2
1546  */
1547 template <class T, class Dealloc>
1548 bool operator<(const SharedLockHandle<T, Dealloc>& s1, const SharedLockHandle<T, Dealloc>& s2) {
1549  return std::less<T>()(s1.get(), s2.get());
1550 }
1551 
1552 #endif // CGU_USE_SMART_PTR_COMPARISON
1553 
1554 } // namespace Cgu
1555 
1556 // doxygen produces long filenames that tar can't handle:
1557 // we have generic documentation for std::hash specialisations
1558 // in doxygen.main.in
1559 #if defined(CGU_USE_SMART_PTR_COMPARISON) && !defined(DOXYGEN_PARSING)
1560 /* These structs allow SharedHandle and SharedLockHandle objects to be
1561  keys in unordered associative containers */
1562 namespace std {
1563 template <class T, class Dealloc>
1564 struct hash<Cgu::SharedHandle<T, Dealloc>> {
1565  typedef std::size_t result_type;
1566  typedef Cgu::SharedHandle<T, Dealloc> argument_type;
1567  result_type operator()(const argument_type& s) const {
1568  // this is fine: std::hash structs do not normally contain data and
1569  // std::hash<T*> certainly won't, so we don't have overhead constructing
1570  // std::hash<T*> on the fly
1571  return std::hash<T>()(s.get());
1572  }
1573 };
1574 template <class T, class Dealloc>
1575 struct hash<Cgu::SharedLockHandle<T, Dealloc>> {
1576  typedef std::size_t result_type;
1577  typedef Cgu::SharedLockHandle<T, Dealloc> argument_type;
1578  result_type operator()(const argument_type& s) const {
1579  // this is fine: std::hash structs do not normally contain data and
1580  // std::hash<T*> certainly won't, so we don't have overhead constructing
1581  // std::hash<T*> on the fly
1582  return std::hash<T>()(s.get());
1583  }
1584 };
1585 } // namespace std
1586 #endif // CGU_USE_SMART_PTR_COMPARISON
1587 
1588 #endif