[Interest] Qt ownership model

Антон Жилин antonyzhilin at gmail.com
Sat Jun 4 14:55:47 CEST 2016


A trend in modern C++ is AAA idiom. It requires all constructions to be of
the following form:

auto x = initial_value;

A major component in this requirement is that most heap allocations should
have the following form:

auto x = make_function<MyType>(constructorArguments);

See std::make_unique, std::make_shared.
The idea here is to *prohibit* new in user code, because ownership
semantics of raw pointer is undefined.

How can we apply these idioms to Qt? Yes, if we add a couple of helper
functions!

1. Non-widgets can usually be constructed on stack or using std::unique_ptr
-- Great

2. If we construct an object with a parent, we do something like this:
auto pushButton = new QPushButton(..., parent);
-- Not so great, we need to look at parent to know if we need to delete
pushButton

3. Widgets without a parent are usually used with QSharedPointer:
auto obj = QSharedPointer<MyObject>::create(...);
-- Not so great, it is verbose and does not line up with standard library

I propose to add two functions to standard library:

template<typename T, typename... Args>
QSharedPointer<T>
QMakeShared(Args&&... args)
{
    return QSharedPointer<T>::create(std::forward<Args>(args)...);
}

template<typename T, typename... Args>
T*
QMakeChild(Args&&... args)
{
    static_assert(std::is_base_of<QObject, T>::value);
    static_assert(last of args is a QObject);
    return new T(std::forward<Args>(args)...);
}

Examples:

auto pushButton = QMakeChild<QPushButton>(...);
auto obj = QMakeShared<MyObject>(...);

auto nonQt = std::make_unique<SomeObject>(...);
auto another = std::make_shared<SomeObject>(...);

Clear and uniform!

Also, it is sometimes needed to remove object between frames only. We can
add another function as a shorthand for this:

auto obj = QSharedPointer<MyObject>(new MyObject, &QObject::deleteLater);

What do you think?

- Anton
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20160604/e1b06f6d/attachment.html>


More information about the Interest mailing list