AUI Framework  master
Cross-platform base for C++ UI apps
Loading...
Searching...
No Matches
AComPtr.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
   15#include <cassert>
   16
   24template<typename T>
   25class AComPtr {
   26public:
   27
   28    AComPtr() {
   29        mValue = nullptr;
   30    }
   31
   32    ~AComPtr() {
   33        if (mValue) {
   34            mValue->Release();
   35        }
   36    }
   37
   38    T** operator&() noexcept {
   39        AUI_ASSERTX(mValue == nullptr, "value already set");
   40        return &mValue;
   41    }
   42
   43    AComPtr(T* value): mValue(value) {}
   44    AComPtr(const AComPtr<T>& rhs): mValue(rhs.mValue) {
   45        if (mValue) {
   46            mValue->AddRef();
   47        }
   48    }
   49
   50    AComPtr(AComPtr<T>&& rhs): mValue(rhs.mValue) {
   51        rhs.mValue = nullptr;
   52    }
   53
   54    [[nodiscard]]
   55    T* value() const noexcept {
   56        AUI_ASSERT(mValue != nullptr);
   57        return mValue;
   58    }
   59
   60    [[nodiscard]]
   61    T* operator*() const noexcept {
   62        return value();
   63    }
   64
   65    [[nodiscard]]
   66    T* operator->() const noexcept {
   67        return value();
   68    }
   69
   70
   71    [[nodiscard]]
   72    operator T*() const noexcept {
   73        return value();
   74    }
   75
   76    [[nodiscard]]
   77    operator bool() const noexcept {
   78        return mValue != nullptr;
   79    }
   80
   81private:
   82    T* mValue;
   83};
   84
   85
#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