Utils: Introduce UniqueObjectPtr

We very often want to remove a Qobject in a scope but because it has a
parent it can be deleted earlier. So using std::unique_ptr can lead to
double deletion. UniqueObjectPtr can track if a pointer is already
deleted. So no double deletion is possible but we still delete the
object in that scope. UniqueObjectPtr is based on std::unique_ptr but
uses a QPointer as internal pointer representation.

Because QPointer is not convertable you cannot cast from one type to
an other(QTBUG-112464). Because of that UniqueObjectInternalPointer
derives from QPointer and adds a conversion constructor.

Change-Id: I2c7707489f6db836cc5db2463efa8c33932b6455
Reviewed-by: Qt CI Bot <qt_ci_bot@qt-project.org>
Reviewed-by: <github-actions-qt-creator@cristianadam.eu>
Reviewed-by: Thomas Hartmann <thomas.hartmann@qt.io>
This commit is contained in:
Marco Bubke
2023-03-30 13:27:34 +02:00
parent a45bc00a0f
commit 48ad79ee1e
6 changed files with 72 additions and 12 deletions

View File

@@ -0,0 +1,58 @@
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
#pragma once
#include <QPointer>
#include <memory.h>
#include <type_traits>
namespace Utils {
namespace Internal {
template<typename Type>
class UniqueObjectInternalPointer : public QPointer<Type>
{
public:
using QPointer<Type>::QPointer;
template<typename UpType,
typename = std::enable_if_t<std::is_convertible_v<UpType *, Type *>
&& !std::is_same_v<std::decay_t<UpType>, std::decay_t<Type>>>>
UniqueObjectInternalPointer(const UniqueObjectInternalPointer<UpType> &p) noexcept
: QPointer<Type>{p.data()}
{}
};
template<typename Type>
struct UniqueObjectPtrDeleter
{
using pointer = UniqueObjectInternalPointer<Type>;
constexpr UniqueObjectPtrDeleter() noexcept = default;
template<typename UpType, typename = std::enable_if_t<std::is_convertible_v<UpType *, Type *>>>
constexpr UniqueObjectPtrDeleter(const UniqueObjectPtrDeleter<UpType> &) noexcept
{}
constexpr void operator()(pointer p) const
{
static_assert(!std::is_void_v<Type>, "can't delete pointer to incomplete type");
static_assert(sizeof(Type) > 0, "can't delete pointer to incomplete type");
delete p.data();
}
};
} // namespace Internal
template<typename Type>
using UniqueObjectPtr = std::unique_ptr<Type, Internal::UniqueObjectPtrDeleter<Type>>;
template<typename Type, typename... Arguments>
auto makeUniqueObjectPtr(Arguments &&...arguments)
{
return UniqueObjectPtr<Type>{new Type(std::forward<Arguments>(arguments)...)};
}
} // namespace Utils