dom/bindings/OwningNonNull.h

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/dom/bindings/OwningNonNull.h	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,87 @@
     1.4 +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
     1.5 +/* vim: set ts=8 sts=2 et sw=2 tw=80: */
     1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.8 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.9 +
    1.10 +/* A class for non-null strong pointers to reference-counted objects. */
    1.11 +
    1.12 +#ifndef mozilla_dom_OwningNonNull_h
    1.13 +#define mozilla_dom_OwningNonNull_h
    1.14 +
    1.15 +#include "nsAutoPtr.h"
    1.16 +
    1.17 +namespace mozilla {
    1.18 +namespace dom {
    1.19 +
    1.20 +template<class T>
    1.21 +class OwningNonNull
    1.22 +{
    1.23 +public:
    1.24 +  OwningNonNull()
    1.25 +#ifdef DEBUG
    1.26 +    : mInited(false)
    1.27 +#endif
    1.28 +  {}
    1.29 +
    1.30 +  operator T&()
    1.31 +  {
    1.32 +    MOZ_ASSERT(mInited);
    1.33 +    MOZ_ASSERT(mPtr, "OwningNonNull<T> was set to null");
    1.34 +    return *mPtr;
    1.35 +  }
    1.36 +
    1.37 +  operator T*()
    1.38 +  {
    1.39 +    MOZ_ASSERT(mInited);
    1.40 +    MOZ_ASSERT(mPtr, "OwningNonNull<T> was set to null");
    1.41 +    return mPtr;
    1.42 +  }
    1.43 +
    1.44 +  void operator=(T* aValue)
    1.45 +  {
    1.46 +    init(aValue);
    1.47 +  }
    1.48 +
    1.49 +  void operator=(const already_AddRefed<T>& aValue)
    1.50 +  {
    1.51 +    init(aValue);
    1.52 +  }
    1.53 +
    1.54 +  already_AddRefed<T> forget()
    1.55 +  {
    1.56 +#ifdef DEBUG
    1.57 +    mInited = false;
    1.58 +#endif
    1.59 +    return mPtr.forget();
    1.60 +  }
    1.61 +
    1.62 +  // Make us work with smart pointer helpers that expect a get().
    1.63 +  T* get() const
    1.64 +  {
    1.65 +    MOZ_ASSERT(mInited);
    1.66 +    MOZ_ASSERT(mPtr);
    1.67 +    return mPtr;
    1.68 +  }
    1.69 +
    1.70 +protected:
    1.71 +  template<typename U>
    1.72 +  void init(U aValue)
    1.73 +  {
    1.74 +    mPtr = aValue;
    1.75 +    MOZ_ASSERT(mPtr);
    1.76 +#ifdef DEBUG
    1.77 +    mInited = true;
    1.78 +#endif
    1.79 +  }
    1.80 +
    1.81 +  nsRefPtr<T> mPtr;
    1.82 +#ifdef DEBUG
    1.83 +  bool mInited;
    1.84 +#endif
    1.85 +};
    1.86 +
    1.87 +} // namespace dom
    1.88 +} // namespace mozilla
    1.89 +
    1.90 +#endif // mozilla_dom_OwningNonNull_h

mercurial