Version 5.2.6.1, tag libreoffice-5.2.6.1
[LibreOffice.git] / onlineupdate / source / update / inc / nsAutoRef.h
bloba159f5954e96caf5ee38c44e5f398433f8cebabf
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef nsAutoRef_h_
8 #define nsAutoRef_h_
10 #include "mozilla/Attributes.h"
12 template <class T> class nsSimpleRef;
13 template <class T> class nsAutoRefBase;
14 template <class T> class nsReturnRef;
15 template <class T> class nsReturningRef;
17 /**
18 * template <class T> class nsAutoRef
20 * A class that holds a handle to a resource that must be released.
21 * No reference is added on construction.
23 * No copy constructor nor copy assignment operators are available, so the
24 * resource will be held until released on destruction or explicitly
25 * |reset()| or transferred through provided methods.
27 * The publicly available methods are the public methods on this class and its
28 * public base classes |nsAutoRefBase<T>| and |nsSimpleRef<T>|.
30 * For ref-counted resources see also |nsCountedRef<T>|.
31 * For function return values see |nsReturnRef<T>|.
33 * For each class |T|, |nsAutoRefTraits<T>| or |nsSimpleRef<T>| must be
34 * specialized to use |nsAutoRef<T>| and |nsCountedRef<T>|.
36 * @param T A class identifying the type of reference held by the
37 * |nsAutoRef<T>| and the unique set methods for managing references
38 * to the resource (defined by |nsAutoRefTraits<T>| or
39 * |nsSimpleRef<T>|).
41 * Often this is the class representing the resource. Sometimes a
42 * new possibly-incomplete class may need to be declared.
45 * Example: An Automatically closing file descriptor
47 * // References that are simple integral types (as file-descriptors are)
48 * // usually need a new class to represent the resource and how to handle its
49 * // references.
50 * class nsRawFD;
52 * // Specializing nsAutoRefTraits<nsRawFD> describes how to manage file
53 * // descriptors, so that nsAutoRef<nsRawFD> provides automatic closing of
54 * // its file descriptor on destruction.
55 * template <>
56 * class nsAutoRefTraits<nsRawFD> {
57 * public:
58 * // The file descriptor is held in an int.
59 * typedef int RawRef;
60 * // -1 means that there is no file associated with the handle.
61 * static int Void() { return -1; }
62 * // The file associated with a file descriptor is released with close().
63 * static void Release(RawRef aFD) { close(aFD); }
64 * };
66 * // A function returning a file descriptor that must be closed.
67 * nsReturnRef<nsRawFD> get_file(const char *filename) {
68 * // Constructing from a raw file descriptor assumes ownership.
69 * nsAutoRef<nsRawFD> fd(open(filename, O_RDONLY));
70 * fcntl(fd, F_SETFD, FD_CLOEXEC);
71 * return fd.out();
72 * }
74 * void f() {
75 * unsigned char buf[1024];
77 * // Hold a file descriptor for /etc/hosts in fd1.
78 * nsAutoRef<nsRawFD> fd1(get_file("/etc/hosts"));
80 * nsAutoRef<nsRawFD> fd2;
81 * fd2.steal(fd1); // fd2 takes the file descriptor from fd1
82 * ssize_t count = read(fd1, buf, 1024); // error fd1 has no file
83 * count = read(fd2, buf, 1024); // reads from /etc/hosts
85 * // If the file descriptor is not stored then it is closed.
86 * get_file("/etc/login.defs"); // login.defs is closed
88 * // Now use fd1 to hold a file descriptor for /etc/passwd.
89 * fd1 = get_file("/etc/passwd");
91 * // The nsAutoRef<nsRawFD> can give up the file descriptor if explicitly
92 * // instructed, but the caller must then ensure that the file is closed.
93 * int rawfd = fd1.disown();
95 * // Assume ownership of another file descriptor.
96 * fd1.own(open("/proc/1/maps");
98 * // On destruction, fd1 closes /proc/1/maps and fd2 closes /etc/hosts,
99 * // but /etc/passwd is not closed.
105 template <class T>
106 class nsAutoRef : public nsAutoRefBase<T>
108 protected:
109 typedef nsAutoRef<T> ThisClass;
110 typedef nsAutoRefBase<T> BaseClass;
111 typedef nsSimpleRef<T> SimpleRef;
112 typedef typename BaseClass::RawRefOnly RawRefOnly;
113 typedef typename BaseClass::LocalSimpleRef LocalSimpleRef;
115 public:
116 nsAutoRef()
120 // Explicit construction is required so as not to risk unintentionally
121 // releasing the resource associated with a raw ref.
122 explicit nsAutoRef(RawRefOnly aRefToRelease)
123 : BaseClass(aRefToRelease)
127 // Construction from a nsReturnRef<T> function return value, which expects
128 // to give up ownership, transfers ownership.
129 // (nsReturnRef<T> is converted to const nsReturningRef<T>.)
130 explicit nsAutoRef(const nsReturningRef<T>& aReturning)
131 : BaseClass(aReturning)
135 // The only assignment operator provided is for transferring from an
136 // nsReturnRef smart reference, which expects to pass its ownership to
137 // another object.
139 // With raw references and other smart references, the type of the lhs and
140 // its taking and releasing nature is often not obvious from an assignment
141 // statement. Assignment from a raw ptr especially is not normally
142 // expected to release the reference.
144 // Use |steal| for taking ownership from other smart refs.
146 // For raw references, use |own| to indicate intention to have the
147 // resource released.
149 // Or, to create another owner of the same reference, use an nsCountedRef.
151 ThisClass& operator=(const nsReturningRef<T>& aReturning)
153 BaseClass::steal(aReturning.mReturnRef);
154 return *this;
157 // Conversion to a raw reference allow the nsAutoRef<T> to often be used
158 // like a raw reference.
159 operator typename SimpleRef::RawRef() const
161 return this->get();
164 // Transfer ownership from another smart reference.
165 void steal(ThisClass& aOtherRef)
167 BaseClass::steal(aOtherRef);
170 // Assume ownership of a raw ref.
172 // |own| has similar function to |steal|, and is useful for receiving
173 // ownership from a return value of a function. It is named differently
174 // because |own| requires more care to ensure that the function intends to
175 // give away ownership, and so that |steal| can be safely used, knowing
176 // that it won't steal ownership from any methods returning raw ptrs to
177 // data owned by a foreign object.
178 void own(RawRefOnly aRefToRelease)
180 BaseClass::own(aRefToRelease);
183 // Exchange ownership with |aOther|
184 void swap(ThisClass& aOther)
186 LocalSimpleRef temp;
187 temp.SimpleRef::operator=(*this);
188 SimpleRef::operator=(aOther);
189 aOther.SimpleRef::operator=(temp);
192 // Release the reference now.
193 void reset()
195 this->SafeRelease();
196 LocalSimpleRef empty;
197 SimpleRef::operator=(empty);
200 // Pass out the reference for a function return values.
201 nsReturnRef<T> out()
203 return nsReturnRef<T>(this->disown());
206 // operator->() and disown() are provided by nsAutoRefBase<T>.
207 // The default nsSimpleRef<T> provides get().
209 private:
210 // No copy constructor
211 explicit nsAutoRef(ThisClass& aRefToSteal);
215 * template <class T> class nsCountedRef
217 * A class that creates (adds) a new reference to a resource on construction
218 * or assignment and releases on destruction.
220 * This class is similar to nsAutoRef<T> and inherits its methods, but also
221 * provides copy construction and assignment operators that enable more than
222 * one concurrent reference to the same resource.
224 * Specialize |nsAutoRefTraits<T>| or |nsSimpleRef<T>| to use this. This
225 * class assumes that the resource itself counts references and so can only be
226 * used when |T| represents a reference-counting resource.
229 template <class T>
230 class nsCountedRef : public nsAutoRef<T>
232 protected:
233 typedef nsCountedRef<T> ThisClass;
234 typedef nsAutoRef<T> BaseClass;
235 typedef nsSimpleRef<T> SimpleRef;
236 typedef typename BaseClass::RawRef RawRef;
238 public:
239 nsCountedRef()
243 // Construction and assignment from a another nsCountedRef
244 // or a raw ref copies and increments the ref count.
245 nsCountedRef(const ThisClass& aRefToCopy)
247 SimpleRef::operator=(aRefToCopy);
248 SafeAddRef();
250 ThisClass& operator=(const ThisClass& aRefToCopy)
252 if (this == &aRefToCopy) {
253 return *this;
256 this->SafeRelease();
257 SimpleRef::operator=(aRefToCopy);
258 SafeAddRef();
259 return *this;
262 // Implicit conversion from another smart ref argument (to a raw ref) is
263 // accepted here because construction and assignment safely creates a new
264 // reference without interfering with the reference to copy.
265 explicit nsCountedRef(RawRef aRefToCopy)
266 : BaseClass(aRefToCopy)
268 SafeAddRef();
270 ThisClass& operator=(RawRef aRefToCopy)
272 this->own(aRefToCopy);
273 SafeAddRef();
274 return *this;
277 // Construction and assignment from an nsReturnRef function return value,
278 // which expects to give up ownership, transfers ownership.
279 explicit nsCountedRef(const nsReturningRef<T>& aReturning)
280 : BaseClass(aReturning)
283 ThisClass& operator=(const nsReturningRef<T>& aReturning)
285 BaseClass::operator=(aReturning);
286 return *this;
289 protected:
290 // Increase the reference count if there is a resource.
291 void SafeAddRef()
293 if (this->HaveResource()) {
294 this->AddRef(this->get());
300 * template <class T> class nsReturnRef
302 * A type for function return values that hold a reference to a resource that
303 * must be released. See also |nsAutoRef<T>::out()|.
306 template <class T>
307 class nsReturnRef : public nsAutoRefBase<T>
309 protected:
310 typedef nsAutoRefBase<T> BaseClass;
311 typedef typename BaseClass::RawRefOnly RawRefOnly;
313 public:
314 // For constructing a return value with no resource
315 nsReturnRef()
319 // For returning a smart reference from a raw reference that must be
320 // released. Explicit construction is required so as not to risk
321 // unintentionally releasing the resource associated with a raw ref.
322 MOZ_IMPLICIT nsReturnRef(RawRefOnly aRefToRelease)
323 : BaseClass(aRefToRelease)
327 // Copy construction transfers ownership
328 nsReturnRef(nsReturnRef<T>& aRefToSteal)
329 : BaseClass(aRefToSteal)
333 MOZ_IMPLICIT nsReturnRef(const nsReturningRef<T>& aReturning)
334 : BaseClass(aReturning)
338 // Conversion to a temporary (const) object referring to this object so
339 // that the reference may be passed from a function return value
340 // (temporary) to another smart reference. There is no need to use this
341 // explicitly. Simply assign a nsReturnRef<T> function return value to a
342 // smart reference.
343 operator nsReturningRef<T>()
345 return nsReturningRef<T>(*this);
348 // No conversion to RawRef operator is provided on nsReturnRef, to ensure
349 // that the return value is not carelessly assigned to a raw ptr (and the
350 // resource then released). If passing to a function that takes a raw
351 // ptr, use get or disown as appropriate.
355 * template <class T> class nsReturningRef
357 * A class to allow ownership to be transferred from nsReturnRef function
358 * return values.
360 * It should not be necessary for clients to reference this
361 * class directly. Simply pass an nsReturnRef<T> to a parameter taking an
362 * |nsReturningRef<T>|.
364 * The conversion operator on nsReturnRef constructs a temporary wrapper of
365 * class nsReturningRef<T> around a non-const reference to the nsReturnRef.
366 * The wrapper can then be passed as an rvalue parameter.
369 template <class T>
370 class nsReturningRef
372 private:
373 friend class nsReturnRef<T>;
375 explicit nsReturningRef(nsReturnRef<T>& aReturnRef)
376 : mReturnRef(aReturnRef)
379 public:
380 nsReturnRef<T>& mReturnRef;
384 * template <class T> class nsAutoRefTraits
386 * A class describing traits of references managed by the default
387 * |nsSimpleRef<T>| implementation and thus |nsAutoRef<T>| and |nsCountedRef|.
388 * The default |nsSimpleRef<T> is suitable for resources with handles that
389 * have a void value. (If there is no such void value for a handle,
390 * specialize |nsSimpleRef<T>|.)
392 * Specializations must be provided for each class |T| according to the
393 * following pattern:
395 * // The template parameter |T| should be a class such that the set of fields
396 * // in class nsAutoRefTraits<T> is unique for class |T|. Usually the
397 * // resource object class is sufficient. For handles that are simple
398 * // integral typedefs, a new unique possibly-incomplete class may need to be
399 * // declared.
401 * template <>
402 * class nsAutoRefTraits<T>
404 * // Specializations must provide a typedef for RawRef, describing the
405 * // type of the handle to the resource.
406 * typedef <handle-type> RawRef;
408 * // Specializations should define Void(), a function returning a value
409 * // suitable for a handle that does not have an associated resource.
410 * //
411 * // The return type must be a suitable as the parameter to a RawRef
412 * // constructor and operator==.
413 * //
414 * // If this method is not accessible then some limited nsAutoRef
415 * // functionality will still be available, but the default constructor,
416 * // |reset|, and most transfer of ownership methods will not be available.
417 * static <return-type> Void();
419 * // Specializations must define Release() to properly finalize the
420 * // handle to a non-void custom-deleted or reference-counted resource.
421 * static void Release(RawRef aRawRef);
423 * // For reference-counted resources, if |nsCountedRef<T>| is to be used,
424 * // specializations must define AddRef to increment the reference count
425 * // held by a non-void handle.
426 * // (AddRef() is not necessary for |nsAutoRef<T>|.)
427 * static void AddRef(RawRef aRawRef);
428 * };
430 * See nsPointerRefTraits for example specializations for simple pointer
431 * references. See nsAutoRef for an example specialization for a non-pointer
432 * reference.
435 template <class T> class nsAutoRefTraits;
438 * template <class T> class nsPointerRefTraits
440 * A convenience class useful as a base class for specializations of
441 * |nsAutoRefTraits<T>| where the handle to the resource is a pointer to |T|.
442 * By inheriting from this class, definitions of only Release(RawRef) and
443 * possibly AddRef(RawRef) need to be added.
445 * Examples of use:
447 * template <>
448 * class nsAutoRefTraits<PRFileDesc> : public nsPointerRefTraits<PRFileDesc>
450 * public:
451 * static void Release(PRFileDesc *ptr) { PR_Close(ptr); }
452 * };
454 * template <>
455 * class nsAutoRefTraits<FcPattern> : public nsPointerRefTraits<FcPattern>
457 * public:
458 * static void Release(FcPattern *ptr) { FcPatternDestroy(ptr); }
459 * static void AddRef(FcPattern *ptr) { FcPatternReference(ptr); }
460 * };
463 template <class T>
464 class nsPointerRefTraits
466 public:
467 // The handle is a pointer to T.
468 typedef T* RawRef;
469 // A nullptr does not have a resource.
470 static RawRef Void()
472 return nullptr;
477 * template <class T> class nsSimpleRef
479 * Constructs a non-smart reference, and provides methods to test whether
480 * there is an associated resource and (if so) get its raw handle.
482 * A default implementation is suitable for resources with handles that have a
483 * void value. This is not intended for direct use but used by |nsAutoRef<T>|
484 * and thus |nsCountedRef<T>|.
486 * Specialize this class if there is no particular void value for the resource
487 * handle. A specialized implementation must also provide Release(RawRef),
488 * and, if |nsCountedRef<T>| is required, AddRef(RawRef), as described in
489 * nsAutoRefTraits<T>.
492 template <class T>
493 class nsSimpleRef : protected nsAutoRefTraits<T>
495 protected:
496 // The default implementation uses nsAutoRefTrait<T>.
497 // Specializations need not define this typedef.
498 typedef nsAutoRefTraits<T> Traits;
499 // The type of the handle to the resource.
500 // A specialization must provide a typedef for RawRef.
501 typedef typename Traits::RawRef RawRef;
503 // Construct with no resource.
505 // If this constructor is not accessible then some limited nsAutoRef
506 // functionality will still be available, but the default constructor,
507 // |reset|, and most transfer of ownership methods will not be available.
508 nsSimpleRef()
509 : mRawRef(Traits::Void())
512 // Construct with a handle to a resource.
513 // A specialization must provide this.
514 explicit nsSimpleRef(RawRef aRawRef)
515 : mRawRef(aRawRef)
519 // Test whether there is an associated resource. A specialization must
520 // provide this. The function is permitted to always return true if the
521 // default constructor is not accessible, or if Release (and AddRef) can
522 // deal with void handles.
523 bool HaveResource() const
525 return mRawRef != Traits::Void();
528 public:
529 // A specialization must provide get() or loose some functionality. This
530 // is inherited by derived classes and the specialization may choose
531 // whether it is public or protected.
532 RawRef get() const
534 return mRawRef;
537 private:
538 RawRef mRawRef;
543 * template <class T> class nsAutoRefBase
545 * Internal base class for |nsAutoRef<T>| and |nsReturnRef<T>|.
546 * Adds release on destruction to a |nsSimpleRef<T>|.
549 template <class T>
550 class nsAutoRefBase : public nsSimpleRef<T>
552 protected:
553 typedef nsAutoRefBase<T> ThisClass;
554 typedef nsSimpleRef<T> SimpleRef;
555 typedef typename SimpleRef::RawRef RawRef;
557 nsAutoRefBase()
561 // A type for parameters that should be passed a raw ref but should not
562 // accept implicit conversions (from another smart ref). (The only
563 // conversion to this type is from a raw ref so only raw refs will be
564 // accepted.)
565 class RawRefOnly
567 public:
568 MOZ_IMPLICIT RawRefOnly(RawRef aRawRef)
569 : mRawRef(aRawRef)
572 operator RawRef() const
574 return mRawRef;
576 private:
577 RawRef mRawRef;
580 // Construction from a raw ref assumes ownership
581 explicit nsAutoRefBase(RawRefOnly aRefToRelease)
582 : SimpleRef(aRefToRelease)
586 // Constructors that steal ownership
587 explicit nsAutoRefBase(ThisClass& aRefToSteal)
588 : SimpleRef(aRefToSteal.disown())
591 explicit nsAutoRefBase(const nsReturningRef<T>& aReturning)
592 : SimpleRef(aReturning.mReturnRef.disown())
596 ~nsAutoRefBase()
598 SafeRelease();
601 // An internal class providing access to protected nsSimpleRef<T>
602 // constructors for construction of temporary simple references (that are
603 // not ThisClass).
604 class LocalSimpleRef : public SimpleRef
606 public:
607 LocalSimpleRef()
610 explicit LocalSimpleRef(RawRef aRawRef)
611 : SimpleRef(aRawRef)
616 private:
617 ThisClass& operator=(const ThisClass& aSmartRef) = delete;
619 public:
620 RawRef operator->() const
622 return this->get();
625 // Transfer ownership to a raw reference.
627 // THE CALLER MUST ENSURE THAT THE REFERENCE IS EXPLICITLY RELEASED.
629 // Is this really what you want to use? Using this removes any guarantee
630 // of release. Use nsAutoRef<T>::out() for return values, or an
631 // nsAutoRef<T> modifiable lvalue for an out parameter. Use disown() when
632 // the reference must be stored in a POD type object, such as may be
633 // preferred for a namespace-scope object with static storage duration,
634 // for example.
635 RawRef disown()
637 RawRef temp = this->get();
638 LocalSimpleRef empty;
639 SimpleRef::operator=(empty);
640 return temp;
643 protected:
644 // steal and own are protected because they make no sense on nsReturnRef,
645 // but steal is implemented on this class for access to aOtherRef.disown()
646 // when aOtherRef is an nsReturnRef;
648 // Transfer ownership from another smart reference.
649 void steal(ThisClass& aOtherRef)
651 own(aOtherRef.disown());
653 // Assume ownership of a raw ref.
654 void own(RawRefOnly aRefToRelease)
656 SafeRelease();
657 LocalSimpleRef ref(aRefToRelease);
658 SimpleRef::operator=(ref);
661 // Release a resource if there is one.
662 void SafeRelease()
664 if (this->HaveResource()) {
665 this->Release(this->get());
670 #endif // !defined(nsAutoRef_h_)