codemod 2010-2016 to 2010-present
[hiphop-php.git] / hphp / util / default-ptr.h
blobc9ad6b92fa23cea2669bc4aa7eed99a141e16843
1 /*
2 +----------------------------------------------------------------------+
3 | HipHop for PHP |
4 +----------------------------------------------------------------------+
5 | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
6 +----------------------------------------------------------------------+
7 | This source file is subject to version 3.01 of the PHP license, |
8 | that is bundled with this package in the file LICENSE, and is |
9 | available through the world-wide-web at the following url: |
10 | http://www.php.net/license/3_01.txt |
11 | If you did not receive a copy of the PHP license and are unable to |
12 | obtain it through the world-wide-web, please send a note to |
13 | license@php.net so we can mail you a copy immediately. |
14 +----------------------------------------------------------------------+
17 #ifndef incl_HPHP_DEFAULT_PTR_H_
18 #define incl_HPHP_DEFAULT_PTR_H_
20 #include <cstddef>
21 #include <utility>
23 namespace HPHP {
24 ///////////////////////////////////////////////////////////////////////////////
27 * Pointer which can be safely const-dereferenced when null to yield a
28 * default-constructed value.
30 template <class T>
31 struct default_ptr {
33 * Constructors.
35 default_ptr() = default;
37 /* implicit */ default_ptr(std::nullptr_t) {}
39 /* implicit */ default_ptr(T* p) : m_p{p ? p : fallback()} {}
42 * Assignments.
44 default_ptr& operator=(std::nullptr_t p) {
45 m_p = fallback();
46 return *this;
48 default_ptr& operator=(T* p) {
49 m_p = p ? p : fallback();
50 return *this;
54 * Observers.
56 const T* get() const {
57 return m_p;
59 const T& operator*() const {
60 return *get();
62 const T* operator->() const {
63 return get();
66 T* raw() const {
67 return m_p == &s_default ? nullptr : m_p;
69 explicit operator bool() const {
70 return raw();
74 * Modifiers.
76 void reset(T* p = nullptr) {
77 operator=(p);
80 private:
82 * Internals.
84 static T* fallback() {
85 return const_cast<T*>(&s_default);
88 private:
89 T* m_p{const_cast<T*>(&s_default)};
90 static const T s_default;
93 template <class T>
94 const T default_ptr<T>::s_default;
96 ///////////////////////////////////////////////////////////////////////////////
99 #endif // incl_HPHP_DEFAULT_PTR_H_