|
| 1 | +/* -*- C++ -*- |
| 2 | + * Cppcheck - A tool for static C/C++ code analysis |
| 3 | + * Copyright (C) 2007-2025 Cppcheck team. |
| 4 | + * |
| 5 | + * This program is free software: you can redistribute it and/or modify |
| 6 | + * it under the terms of the GNU General Public License as published by |
| 7 | + * the Free Software Foundation, either version 3 of the License, or |
| 8 | + * (at your option) any later version. |
| 9 | + * |
| 10 | + * This program is distributed in the hope that it will be useful, |
| 11 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | + * GNU General Public License for more details. |
| 14 | + * |
| 15 | + * You should have received a copy of the GNU General Public License |
| 16 | + * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 | + */ |
| 18 | + |
| 19 | +//--------------------------------------------------------------------------- |
| 20 | +#ifndef safePtrH |
| 21 | +#define safePtrH |
| 22 | +//--------------------------------------------------------------------------- |
| 23 | + |
| 24 | +#include "config.h" |
| 25 | + |
| 26 | +// as std::optional behaves similarly so we could use that instead of if we ever move to C++17. |
| 27 | +// it is not a simple drop-in as our "operator bool()" indicates if the pointer is non-null |
| 28 | +// whereas std::optional indicates if a value is set. |
| 29 | +// |
| 30 | +// This is similar to std::experimental::propagate_const |
| 31 | +// see https://en.cppreference.com/w/cpp/experimental/propagate_const |
| 32 | +template<typename T> |
| 33 | +class safe_ptr |
| 34 | +{ |
| 35 | +public: |
| 36 | + explicit safe_ptr(T* p) |
| 37 | + : mPtr(p) |
| 38 | + {} |
| 39 | + |
| 40 | + T* get() NOEXCEPT { |
| 41 | + return mPtr; |
| 42 | + } |
| 43 | + |
| 44 | + const T* get() const NOEXCEPT { |
| 45 | + return mPtr; |
| 46 | + } |
| 47 | + |
| 48 | + T* operator->() NOEXCEPT { |
| 49 | + return mPtr; |
| 50 | + } |
| 51 | + |
| 52 | + const T* operator->() const NOEXCEPT { |
| 53 | + return mPtr; |
| 54 | + } |
| 55 | + |
| 56 | + T& operator*() NOEXCEPT { |
| 57 | + return *mPtr; |
| 58 | + } |
| 59 | + |
| 60 | + const T& operator*() const NOEXCEPT { |
| 61 | + return *mPtr; |
| 62 | + } |
| 63 | + |
| 64 | + explicit operator bool() const NOEXCEPT { |
| 65 | + return mPtr != nullptr; |
| 66 | + } |
| 67 | + |
| 68 | +private: |
| 69 | + T* mPtr; |
| 70 | +}; |
| 71 | + |
| 72 | +#endif // safePtrH |
0 commit comments