AUI Framework  develop
Cross-platform base for C++ UI apps
Loading...
Searching...
No Matches
AGlibPtr.h
    1/*
    2 * AUI Framework - Declarative UI toolkit for modern C++20
    3 * Copyright (C) 2020-2025 Alex2772 and Contributors
    4 *
    5 * SPDX-License-Identifier: MPL-2.0
    6 *
    7 * This Source Code Form is subject to the terms of the Mozilla Public
    8 * License, v. 2.0. If a copy of the MPL was not distributed with this
    9 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
   10 */
   11
   12#pragma once
   13
   14#include <cassert>
   15#include <glib-object.h>
   16
   24template<typename T>
   25class AGlibPtr {
   26public:
   27    AGlibPtr() = default;
   28
   29    ~AGlibPtr() {
   30        release();
   31    }
   32
   33    void release() {
   34        if (!mValue) {
   35            return;
   36        }
   37        g_object_unref(mValue);
   38        mValue = nullptr;
   39    }
   40
   41    T** operator&() noexcept {
   42        AUI_ASSERTX(mValue == nullptr, "value already set");
   43        return &mValue;
   44    }
   45
   46    AGlibPtr(T* value): mValue(value) {}
   47    AGlibPtr(const AGlibPtr<T>& rhs): mValue(rhs.mValue) {
   48        if (mValue) {
   49            g_object_ref(mValue);
   50        }
   51    }
   52
   53    AGlibPtr& operator=(T* value) {
   54        release();
   55        mValue = value;
   56        return *this;
   57    }
   58
   59    AGlibPtr(AGlibPtr<T>&& rhs): mValue(rhs.mValue) {
   60        rhs.mValue = nullptr;
   61    }
   62
   63    [[nodiscard]]
   64    T* value() const noexcept {
   65        AUI_ASSERT(mValue != nullptr);
   66        return mValue;
   67    }
   68
   69    [[nodiscard]]
   70    T* operator*() const noexcept {
   71        return value();
   72    }
   73
   74    [[nodiscard]]
   75    T* operator->() const noexcept {
   76        return value();
   77    }
   78
   79
   80    [[nodiscard]]
   81    operator T*() const noexcept {
   82        return value();
   83    }
   84
   85    [[nodiscard]]
   86    operator bool() const noexcept {
   87        return mValue != nullptr;
   88    }
   89
   90private:
   91    T* mValue = nullptr;
   92};
#define AUI_ASSERT(condition)
Asserts that the passed condition evaluates to true.
Definition Assert.h:55
#define AUI_ASSERTX(condition, what)
Asserts that the passed condition evaluates to true. Adds extra message string.
Definition Assert.h:74