As indicated in Bjarne Stroustrup "Tour of C ++", and as a well-known practice of C ++ 14, avoid naked newand deletein the code. The standard library offers std::make_sharedand std::make_uniqueto create smart pointers for the immediate storage of selected objects.
However, these routines cannot be used for non-standard smart pointers, such as in Qt. Qt has its own memory management model (with parents), but it also provides smart pointer classes, such as QSharedPointerand QPointer(although the latter is not actually an own pointer).
My question is: is it not convenient to create Qt analogues std::make_shared? For example, to create QSharedPtr:
namespace Qt
{
template<class T, class... Args>
QSharedPointer<T> make_shared(Args&&... args)
{
return QSharedPointer<T>(new T(std::forward<Args>(args)...));
}
}
Or, for example, to create QPointer:
namespace Qt
{
template<class T, class... Args>
QPointer<T> make_ptr(Args&&... args)
{
return QPointer<T>(new T(std::forward<Args>(args)...));
}
}
And it can be used as:
auto pCancelButton = Qt::make_ptr<QPushButton>("Cancel", this);
Are there any warnings for this approach? Is there a well-known use of this approach?
The UPDATE . I argue that it Qt::make_ptris useful if it is useful to use QPointer, because it will hide the operator newand make sure that it newis called only for what it inherits QObject. Qt users do a lot new, but in this way we can be sure that it is newused only in the context of Qt. Any arguments in favor of this thought?
source
share