3

I've been working with Qt for somedays and I wonder why all their API uses plain pointers instead of their own smart pointers like QSharedPointer.

Wouldn't it be more consistent to use them?

demonplus
  • 5,613
  • 12
  • 49
  • 68
Basti Funck
  • 1,400
  • 17
  • 31
  • 1
    as gomons says, QSharedPointer were an addon pretty late in the game, when the Qt basics were already set. And you can't replace raw pointers with shared pointers without thinking, otherwise you end up with cycles. Thus forcing Qt users to port their potentially large codebases from raw pointers to shared pointers would be a nightmare. – Frank Osterfeld Apr 11 '15 at 21:28

2 Answers2

7

QSharedPointer is implemented since Qt 4.5. In Qt, QObjects organize themselves in object trees. When you create a QObject, with another object as the parent, the former is added to the latter's children list and destroyed in the latter's destructor. So you do not need to use QSharedPointer with its overhead.

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
gomons
  • 1,946
  • 14
  • 25
6

Why should QSharedPointer be used when in Qt APIs object ownership is usually exclusive to one object? There is no need for sharing.

A more appropriate question would be why is Qt using raw pointers instead of smart pointers (be those Qt's or C++11's), and the reason for this is simple - those are new features, and even though Qt 5 has been released after C++11 (and internally employs it), rewriting everything to use smart pointers besides tedious will also result in annihilation of backward comparability of user code.

Overall, Qt APIs seem to be somewhat lacking and incoherent in this regard. For example - it is a major inconvenience that Qt's smart pointers are not supported in QtQuick, which uses its own private smart pointer implementation, so you should either have ownership managed by the QML engine or by C++, but you cannot really share across the two.

dtech
  • 47,916
  • 17
  • 112
  • 190