As stated in Bjarne Stroustrup's "A tour of C++", and as a known C++14 practice, one should avoid naked new and delete in the code. Standard library offers std::make_shared and std::make_unique for creating smart pointers to immediately store allocated objects in.
However, it is not possible to use these routines for non-standard smart pointers, like in Qt. Qt has its own memory management model (with parents), but also provides smart pointer classes like QSharedPointer and QPointer (though the latter is not actually an owning pointer).
My question is: isn't it convenient to create Qt analogs of std::make_shared? Like this, for creating QSharedPtr:
namespace Qt
{
template<class T, class... Args>
QSharedPointer<T> make_shared(Args&&... args)
{
return QSharedPointer<T>(new T(std::forward<Args>(args)...));
}
}
Or like this, for creating 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 like:
auto pCancelButton = Qt::make_ptr<QPushButton>("Cancel", this);
Are there any caveats for this approach? Are there any publicly known usage of this approach?
UPDATE I claim that Qt::make_ptr is useful as long as QPointer is useful, because it will hide new operator and make sure new is called only for something that inherits QObject. Qt users do a lot of new's, but in this way we can be sure new is used only in Qt context. Any arguments on this thought?
QPointer?make_with_parentwould be better thanmake_ptrbecause the important thing is that the object's lifetime is managed by the parent. The specific type of non-owning pointer used to refer to the object is irrelevant. Forcing the use ofQPointerwould add unnecessary overhead in cases where a raw pointer would be sufficient.QPointerit probably wouldn't make sense to combine the allocation of storage for the object and storage for the refcount in a single allocation of heap memory, because the refcount would be expected to outlive the object.