Idea for not-null pointer type support in the Qt API
-
Hi,
In the Qt API there are a lot of places where:
- Methods or functions have pointer arguments that may not be null. (passing null would give undefined behaviour)
- Methods or functions return pointers that can never be null.
It would be great if this can be put in code instead of (just) in documentation. This would make it more clear to developers that a pointer cannot be null, but, more importantly, it will give compilers and linters an oppertunity to spot bugs in code. I'm thinking about (something like) the not_null template in Microsoft's Guidelines Support Library. See this C++ Core Guidelines article or this C++ Stories article for an explanation.
Examples:
void QUndoGroup::addStack(QUndoStack *stack)
would become
void QUndoGroup::addStack(not_null<QUndoStack*> stack)
QAction* QWidget::addAction(const QString &text)
would become
not_null<QAction*> QWidget::addAction(const QString &text)
.
An other advantage of this is that language bindings for programming languages that distinguish between possibly-null and not-null in their type system, such as Kotlin, can be made better. See this QtJambi discussion (Java/Kotlin language bindings).
Adding such support would be a lot of work, but it doesn't have to be done in one single go. It can be done one class or module at a time.
What are your thoughts on this?
-
The place for such discussions is on Qt Develop mailing list.
Does this change impact binary compatibility? If so, then such change can only be made in Qt 7.0. So this point is not necessarily valid:
it doesn't have to be done in one single go.
-
I think keeping compatibility with existing sources and binaries is necessary for this idea to gain any popularity. I'm not skilled enough in C++ to fully understand the implications of using the
not_null
template method. Another approach is to use a macro:#define NOT_NULL(x) x
The examples in my first post would look like this:
void QUndoGroup::addStack(NOT_NULL(QUndoStack*) stack)
NOT_NULL(QAction*) QWidget::addAction(const QString &text)
This keeps compatibility without making things complicated.
I'll post it on the mailing list later.
-
@Paul-Breeuwsma said in Idea for not-null pointer type support in the Qt API:
passing null would give undefined behaviour
99.9999999% of the times passing null is segfault.
QUndoGroup::addStack
is a great example. Its an easy crash to debugI feel like the concept of "not null pointer" already exists in C++, it's called a reference. Qt already uses references as never-null-pointers internally in the D-Pointer architecture (e.g.
QObject::QObject(QObjectPrivate &dd, QObject *parent)
where the first argument is actually a pointer that is never null). It just turns out sometimes it's more confusing to use the reference than having an explicit pointer