|
| 1 | +/* -*- C++ -*- |
| 2 | + * Cppcheck - A tool for static C/C++ code analysis |
| 3 | + * Copyright (C) 2007-2026 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 refthunkH |
| 21 | +#define refthunkH |
| 22 | +//--------------------------------------------------------------------------- |
| 23 | + |
| 24 | +#include <memory> |
| 25 | + |
| 26 | +/** |
| 27 | + * Reference wrapper whose operator() returns the referenced object. |
| 28 | + * |
| 29 | + * It is constructed from a reference and converts implicitly back to one |
| 30 | + * (like std::reference_wrapper), so it can replace a reference data member |
| 31 | + * without changing the constructor or call sites that pass the member to |
| 32 | + * functions taking T&. Unlike a reference member it is copyable and |
| 33 | + * assignable; assignment rebinds it. |
| 34 | + */ |
| 35 | +template<class T> |
| 36 | +struct RefThunk { |
| 37 | + RefThunk() = delete; |
| 38 | + |
| 39 | + // cppcheck-suppress noExplicitConstructor |
| 40 | + // NOLINTNEXTLINE(google-explicit-constructor) |
| 41 | + constexpr RefThunk(T& t) noexcept : mPtr(std::addressof(t)) {} |
| 42 | + RefThunk(T&& t) = delete; |
| 43 | + |
| 44 | + constexpr T& operator()() const noexcept { |
| 45 | + return *mPtr; |
| 46 | + } |
| 47 | + |
| 48 | + constexpr T& get() const noexcept { |
| 49 | + return *mPtr; |
| 50 | + } |
| 51 | + |
| 52 | + // NOLINTNEXTLINE(google-explicit-constructor) |
| 53 | + constexpr operator T&() const noexcept { |
| 54 | + return *mPtr; |
| 55 | + } |
| 56 | + |
| 57 | +private: |
| 58 | + T* mPtr; |
| 59 | +}; |
| 60 | + |
| 61 | +#endif |
0 commit comments