Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

QScopedPointer Class Reference
[QtCore module]

The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction. More...

 #include <QScopedPointer>

Inherited by QScopedArrayPointer.

Note: All functions in this class are reentrant.

This class was introduced in Qt 4.6.


Public Functions

QScopedPointer ( T * p = 0 )
~QScopedPointer ()
T * data () const
bool isNull () const
void reset ( T * other = 0 )
void swap ( QScopedPointer<T, Cleanup> & other )
T * take ()
operator bool () const
bool operator! () const
T & operator* () const
T * operator-> () const

Detailed Description

The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction.

Managing heap allocated objects manually is hard and error prone, with the common result that code leaks memory and is hard to maintain. QScopedPointer is a small utility class that heavily simplifies this by assigning stack-based memory ownership to heap allocations, more generally called resource acquisition is initialization(RAII).

QScopedPointer guarantees that the object pointed to will get deleted when the current scope disappears.

Consider this function which does heap allocations, and have various exit points:

 void myFunction(bool useSubClass)
 {
     MyClass *p = useSubClass ? new MyClass() : new MySubClass;
     QIODevice *device = handsOverOwnership();

     if (m_value > 3) {
         delete p;
         delete device;
         return;
     }

     try {
         process(device);
     }
     catch (...) {
         delete p;
         delete device;
         throw;
     }

     delete p;
     delete device;
 }

It's encumbered by the manual delete calls. With QScopedPointer, the code can be simplified to:

 void myFunction(bool useSubClass)
 {
     // assuming that MyClass has a virtual destructor
     QScopedPointer<MyClass> p(useSubClass ? new MyClass() : new MySubClass);
     QScopedPointer<QIODevice> device(handsOverOwnership());

     if (m_value > 3)
         return;

     process(device);
 }

The code the compiler generates for QScopedPointer is the same as when writing it manually. Code that makes use of delete are candidates for QScopedPointer usage (and if not, possibly another type of smart pointer such as QSharedPointer). QScopedPointer intentionally has no copy constructor or assignment operator, such that ownership and lifetime is clearly communicated.

The const qualification on a regular C++ pointer can also be expressed with a QScopedPointer:

     const QWidget *const p = new QWidget();
     // is equivalent to:
     const QScopedPointer<const QWidget> p(new QWidget());

     QWidget *const p = new QWidget();
     // is equivalent to:
     const QScopedPointer<QWidget> p(new QWidget());

     QWidget *const p = new QWidget();
     // is equivalent to:
     const QScopedPointer<QWidget> p(new QWidget());

     const QWidget *p = new QWidget();
     // is equivalent to:
     QScopedPointer<const QWidget> p(new QWidget());

Custom cleanup handlers

Arrays as well as pointers that have been allocated with malloc must not be deleted using delete. QScopedPointer's second template parameter can be used for custom cleanup handlers.

The following custom cleanup handlers exist:

  • QScopedPointerDeleter - the default, deletes the pointer using delete
  • QScopedPointerArrayDeleter - deletes the pointer using delete []. Use this handler for pointers that were allocated with new [].
  • QScopedPointerPodDeleter - deletes the pointer using free(). Use this handler for pointers that were allocated with malloc().

You can pass your own classes as handlers, provided that they have a public static function void cleanup(T *pointer).

 // this QScopedPointer deletes its data using the delete[] operator:
 QScopedPointer<int, QScopedPointerArrayDeleter<int> > arrayPointer(new int[42]);

 // this QScopedPointer frees its data using free():
 QScopedPointer<int, QScopedPointerPodDeleter> podPointer(reinterpret_cast<int *>(malloc(42)));

 // this struct calls "myCustomDeallocator" to delete the pointer
 struct ScopedPointerCustomDeleter
 {
     static inline void cleanup(MyCustomClass *pointer)
     {
         myCustomDeallocator(pointer);
     }
 };

 // QScopedPointer using a custom deleter:
 QScopedPointer<MyCustomClass, ScopedPointerCustomDeleter> customPointer(new MyCustomClass);

Forward Declared Pointers

Classes that are forward declared can be used within QScopedPointer, as long as the destructor of the forward declared class is available whenever a QScopedPointer needs to clean up.

Concretely, this means that all classes containing a QScopedPointer that points to a forward declared class must have non-inline constructors, destructors and assignment operators:

 class MyPrivateClass; // forward declare MyPrivateClass

 class MyClass
 {
 private:
     QScopedPointer<MyPrivateClass> privatePtr; // QScopedPointer to forward declared class

 public:
     MyClass(); // OK
     inline ~MyClass() {} // VIOLATION - Destructor must not be inline

 private:
     Q_DISABLE_COPY(MyClass) // OK - copy constructor and assignment operators
                              // are now disabled, so the compiler won't implicitely
                              // generate them.
 };

Otherwise, the compiler output a warning about not being able to destruct MyPrivateClass.

See also QSharedPointer.


Member Function Documentation

QScopedPointer::QScopedPointer ( T * p = 0 )

Constructs this QScopedPointer instance and sets its pointer to p.

QScopedPointer::~QScopedPointer ()

Destroys this QScopedPointer object. Delete the object its pointer points to.

T * QScopedPointer::data () const

Returns the value of the pointer referenced by this object. QScopedPointer still owns the object pointed to.

bool QScopedPointer::isNull () const

Returns true if this object is holding a pointer that is null.

void QScopedPointer::reset ( T * other = 0 )

Deletes the existing object it is pointing to if any, and sets its pointer to other. QScopedPointer now owns other and will delete it in its destructor.

void QScopedPointer::swap ( QScopedPointer<T, Cleanup> & other )

Swap this pointer with other.

T * QScopedPointer::take ()

Returns the value of the pointer referenced by this object. The pointer of this QScopedPointer object will be reset to null.

Callers of this function take ownership of the pointer.

QScopedPointer::operator bool () const

Returns true if this object is not null. This function is suitable for use in if-constructs, like:

 if (scopedPointer) {
     ...
 }

See also isNull().

bool QScopedPointer::operator! () const

Returns true if the pointer referenced by this object is null, otherwise returns false.

See also isNull().

T & QScopedPointer::operator* () const

Provides access to the scoped pointer's object.

If the contained pointer is null, behavior is undefined.

See also isNull().

T * QScopedPointer::operator-> () const

Provides access to the scoped pointer's object.

If the contained pointer is null, behavior is undefined.

See also isNull().

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 64
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. La rubrique Qt a besoin de vous ! 1
Page suivante

Le blog Digia au hasard

Logo

Déploiement d'applications Qt Commercial sur les tablettes Windows 8

Le blog Digia est l'endroit privilégié pour la communication sur l'édition commerciale de Qt, où des réponses publiques sont apportées aux questions les plus posées au support. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.6
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web