![]() |
Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
|
Classes | |
| struct | DefaultDeleter |
| struct | FileDescriptorHandleTraits |
| struct | FILEHandleTraits |
QUniqueHandle is a general purpose RAII wrapper intended for interfacing with resource-allocating C-style APIs, for example operating system APIs, database engine APIs, or any other scenario where resources are allocated and released, and where pointer semantics does not seem a perfect fit.
QUniqueHandle does not support copying, because it is intended to maintain ownership of resources that can not be copied. This makes it safer to use than naked handle types, since ownership is maintained by design.
The underlying handle object is described using a client supplied HandleTraits object that is implemented per resource type. The traits struct must describe two properties of a handle:
1) What value is considered invalid 2) How to close a resource.
Example 1:
struct InvalidHandleTraits {
using Type = HANDLE;
static Type invalidValue() {
return INVALID_HANDLE_VALUE;
}
static bool close(Type handle) {
return CloseHandle(handle) != 0;
}
}
using FileHandle = QUniqueHandle<InvalidHandleTraits>;
Usage:
Takes ownership of returned handle. FileHandle handle{ CreateFile(...) };
if (!handle.isValid()) { qDebug() << GetLastError() return; }
...
Example 2:
struct SqLiteTraits {
using Type = sqlite3*;
static Type invalidValue() {
return nullptr;
}
static bool close(Type handle) {
sqlite3_close(handle);
return true;
}
}
using DbHandle = QUniqueHandle<SqLiteTraits>;
Usage:
DbHandle h;
Take ownership of returned handle. int result = sqlite3_open(":memory:", &h);
...
Example 3:
struct TempFileTraits {
using Type = FILE*;
static Type invalidValue() {
return nullptr;
}
static bool close(Type handle) {
return fclose(handle) == 0;
}
};
struct TempFileDeleter {
using Type = TempFileTraits::Type;
void operator()(Type handle) {
if (handle != TempFileTraits::invalidValue()) {
TempFileTraits::close(handle);
if (path)
remove(path);
}
}
const char* path{ nullptr };
};
using TempFileHandle = QUniqueHandle<TempFileTraits, TempFileDeleter>;
Usage:
TempFileHandle tempFile(fopen("temp.bin", "wb"), TempFileDeleter{ "my_temp.bin" });
...
NOTE: The QUniqueHandle assumes that closing a resource is guaranteed to succeed, and provides no support for handling failure to close a resource. It is therefore only recommended for use cases where failure to close a resource is either not an error, or an unrecoverable error.