Smart pointers in Qt [duplicate]

2019-04-18 06:49发布

问题:

This question already has an answer here:

  • What C++ Smart Pointer Implementations are available? 3 answers

Like it has been written here Qt up to now has 8 specilized smart pointer classes. It looks like it is all you will ever need. However, in order to use any of these smart pointers your class must be derived from QObject which is not always convenient. Is there other implementations of smart pointers in Qt which work with arbitrary classes?

回答1:

Many Qt classes are derived from QObject, and while some of the built in smart pointer classes are related to QObject (or QSharedData), the QSharedPointer and QScopedPointer templates appear to allow pointers to anything.

Beyond that, you'll find some smart pointer templates in Boost:

  • scoped_ptr - Simple sole ownership of single objects. Noncopyable.
  • scoped_array - Simple sole ownership of arrays. Noncopyable.
  • shared_ptr - Object ownership shared among multiple pointers.
  • shared_array - Array ownership shared among multiple pointers.
  • weak_ptr - Non-owning observers of an object owned by shared_ptr.
  • intrusive_ptr - Shared ownership of objects with an embedded reference count.