QT Smart Pointer Learning (7 kinds of QT Smart pointers and 4 STD smart pointers)

Source: Internet
Author: User

Starting from a memory leak?

Very simple entry procedure, you should be familiar with it ^_^

#include <QApplication> #include <qlabel>int main (int argc, char *argv[]) {    qapplication app (argc, argv) ;    Qlabel *label = new Qlabel ("Hello dbzhang800!");    Label->show ();    return app.exec ();}

In the context of the delete from Qt, we mentioned that the program has a memory leak (the representation is that the destructor is not called), and there are three workarounds:

    • Assigning a Label object to a stack instead of a heap
    • Set tag bit qt::wa_deleteonclose for label

    • Call Delete yourself to delete the Label object that is assigned to the heap by new

Note:

    • In order to be able to clearly observe the invocation of the structure and destructor, we can simply subclass the Qlabel and replace the previous Qlabel with a label.
      Class label:p ublic qlabel{public:    label (const qstring& text, Qwidget *parent=null)        : Qlabel (text, parent) { Qdebug ("from constructor");}    ~label () {qdebug ("from destructor");};

In this article, we continue to consider this issue from the smart pointer (smart pointer) perspective

Smart pointers

To manage resources such as memory, C + + programmers typically use the RAII (Resource acquisition is initialization) Mechanism: Request a resource in the class's constructor, then use it, and finally release the resource in the destructor.

Without a smart pointer, the programmer must ensure that the new object can delete at the right time, write exception capture code around to free resources, and the smart pointer can always call delete when exiting the scope (whether it is a normal process or leaving because of an exception) to deconstruct dynamically allocated objects on the heap.

Let's look at the Qt family's smart pointers:

Smart pointers

Introduced

Qpointer

Features of the Qt Object model (one)
Note: Destructors do not delete resources that it manages

Qsharedpointer

With reference count

Qt4.5

Qweakpointer

Qt4.5

Qscopedpointer

Qt4.6

Qscopedarraypointer

Derived classes for Qscopedpointer

Qt4.6

Qshareddatapointer

Implicit sharing for QT (implicit sharing)

Qt4.0

Qexplicitlyshareddatapointer

Explicit sharing

Qt4.4

Std::auto_ptr

Std::shared_ptr

Std::tr1::shared_ptr

c++0x

Std::weak_ptr

Std::tr1::weak_ptr

c++0x

Std::unique_ptr

Boost::scoped_ptr

c++0x

Note:

    • MSVC2010 and GCC g++ 4.3 support c++0x
    • MSVC2008 SP1 and GCC g++ 4.0 support TR1

With these things, we can easily transform our previous example (just change one line):

Std::auto_ptr<qlabel> label (New Qlabel ("Hello dbzhang800!"));

Depending on the version of QT you are using, and the support level of the C + + compiler, you can choose from:

    • Qscopedpointer
    • Std::unique_ptr
    • Qsharedpointer
    • Std::shared_ptr
      • Std::tr1::shared_ptr
Qpointer

How do you translate it? I'm not sure, keep it in English.

    • The Qpointer class is a template class, provides guarded pointers to qobjects.

    • Use: A guarded pointer,qpointer<t>, behaves like a regular pointer T *

    • Feature: When the object it points to (T must be qobject and its derived class) is destroyed, it is automatically null.
      • Note: The guarded object is not automatically destroyed when it is destructor itself
    • Purpose: This is useful when you need to save pointers to Qobject objects owned by other people

An example

     qpointer<qlabel> label = new Qlabel;     Label->settext ("&status:");     ...     if (label)         label->show ();

If you are in ... section you delete the object, and the label automatically resets null instead of a hanging (dangling) wild pointer.

Qpointer belongs to one of the core mechanisms of the QT object model, notice the difference between the other smart pointers.

Std::auto_ptr

This is not much to say.

    • You cannot have multiple auto_ptr pointing to the same object! (When Auto_ptr is destroyed, it automatically deletes the object it points to, so the object is deleted more than once)
      • When manipulated by copying constructs or assignments, the copy is automatically null, and the copied pointer obtains the unique ownership of the resource
    • A smart pointer cannot point to an array (because the implementation calls the delete instead of delete[])
    • A smart pointer cannot be an element of a container class.

In c++0x, Auto_ptr is not recommended and should be replaced by 3 other smart pointers in the future.

Qscopedpointer and Std::unique_ptr

They should be the same conceptually. The following are no longer differentiated:

This is a smart pointer similar to AUTO_PTR, which wraps the dynamic objects allocated on the heap by the new operator, ensuring that dynamically created objects can be correctly deleted at any time. However, its ownership is more stringent and cannot be transferred, and once the management of the object has been acquired, you will no longer be able to take it back from it.

Both Qscopedpointer and std::unique_ptr have a good name, which conveys a clear message to the reader of the code: this smart pointer can only be used in this scope and is not intended to be transferred. Because its copy construction and assignment operations are private, we can compare the objects of Qobject and its derived classes.

usage (Manual from QT):

Consider a situation where there is no smart pointer,

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; }

We write DELETE statements more than once in an exception-handling statement, which can cause a resource leak if you accidentally do so. With smart pointers, we can simplify these exception handling statements:

void MyFunction (bool usesubclass) {     qscopedpointer<myclass> p (usesubclass new MyClass (): New MySubClass); C18/>qscopedpointer<qiodevice> Device (Handsoverownership ());     if (M_value > 3)         return;     process (device); }

Also, our first example is the best place to use these two pointers (the object that the main function is scoped to destroys).

Note: Because copy construction and assignment operations are private, it also has auto_ptr the same "flaw"--the element that cannot be used as a container.

Qsharedpointer and Std::shared_ptr

Qsharedpointer and Std::shared_ptr Act closest to the original pointer, which is the "smart pointer" that is most like the pointer, with a wider range of applications than previously mentioned.

Qsharedpointer, like Qscopedpointer, wraps the dynamic object assigned by the new operator on the heap, but it implements a reference-counting smart pointer that can be freely copied and assigned, shared anywhere, When no code is used (the reference count is 0) it removes the wrapped dynamically allocated object. Shared_ptr can also be safely placed in standard containers and make up for std::auto_ptr and qscopedpointer defects that cannot be used as container elements because of the transfer semantics.

Qweakpointer and Std::weak_ptr

The strong reference type of the qsharedpointer has been very useful, why should there be a weak reference to the Qweakpointer?

Qweakpointer is a smart pointer introduced to fit the Qsharedpointer, which is more like an assistant to Qsharedpointer (because it does not behave as a normal pointer, and does not overload operator* and). Its biggest role is to help qsharedpointer work, like a bystander to observe the use of resources.

  • The
  • weak_ptr is primarily designed to avoid strong references forming loops. Excerpt from MSDN:
    • A cycle occurs when both or more resources controlled by shared_ptr objects hold mutually referenci Ng shared_ptr objects. For example, a circular linked list with three elements have a head node N0; That node holds a shared_ptr object that owns the next node, N1; That node holds a shared_ptr object that owns the next node, N2; That node, in turn, holds a shared_ptr object that owns the head node, N0, closing the cycle. In this situation, none of the reference counts would ever become zero, and the nodes in the cycle won't be freed. To eliminate the cycle, the last node N2 should hold a Weak_ptr object pointing to N0 instead of a shared_ptr object. Since the Weak_ptr object does not own N0 it doesn ' t affect N0 ' s reference count, and if the program's last reference to The head node is destroyed the nodes in the list would also be destroyed.
  • In Qt, Qweakpointer has special handling for Qobject and its derived class objects. It can be used as a substitute for qpointer.
    • In this case, the presence of qsharedpointer is not required
    • Higher efficiency than Qpointer
Qshareddatapointer

This is a handy tool for implementing implicit sharing (copy-on-write copy-on-write) with Qshareddata.

Many of the classes in QT use implicit sharing techniques such as Qpixmap, Qbytearray, QString 、...。 It is also simple to implement implicit sharing for our classes, such as implementing an employee class:

    • Defines an Employee class that contains only one data member (qshareddatapointer<employeedata>)

    • All of the data members we need are placed in the EmployeeData class derived from Qshareddata.

The concrete realization sees Qshareddatapointer's manual, here slightly

Qexplicitlyshareddatapointer

This is a handy tool for implementing explicit sharing with Qshareddata.

Qexplicitlyshareddatapointer and Qshareddatapointer are very similar, but it disables the copy-on-write feature. This makes the object we create more like a pointer.

An example, followed by the employee in front:

#include "employee.h" int main () {     employee E1 (1001, "Albrecht Durer");     Employee e2 = e1;     E1.setname ("Hans Holbein"); }

Copy-on-write technology causes: E1 and E2 have the same work number, but have different names. Unlike what we expected, explicit sharing can solve this problem, which also makes the employee itself more like a pointer.

Addendum
I didn't notice the official two articles before (this was a failure):
    • http://labs.qt.nokia.com/2009/08/25/count-with-me-how-many-smart-pointer-classes-does-qt-have/
    • http://labs.qt.nokia.com/2009/08/21/introducing-qscopedpointer/
Take a look at the recommendations in the Google Code specification for 3 Smart pointers:
scoped_ptr
Straightforward and Risk-free. Use wherever appropriate.
auto_ptr
Confusing and bug-prone ownership-transfer semantics. Do not use.
shared_ptr
Safe with const referents (i.e. shared_ptr<const T> ). reference-counted pointers with Non-const referents can occasionally is the best design, but try-to-rewrite with a single ow Ners where possible.
Reference
    • Qt Manual
    • Smart Pointers FAQ

    • The New c++:smart (er) pointers

    • Http://en.wikipedia.org/wiki/Smart_pointer

    • C + +: Introduction to shared_ptr and weak_ptr use of smart pointer-tr1

    • Standard contention for "C++boost" smart pointers: Boost vs. Loki

    • Http://www2.research.att.com/~bs/C++0xFAQ.html

    • Http://msdn.microsoft.com/zh-cn/library/bb982126.aspx

    • http://www.codesynthesis.com/~boris/blog/2010/05/24/smart-pointers-in-boost-tr1-cxx-x0/

    • Http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml

http://blog.csdn.net/dbzhang800/article/details/6403285

QT Smart Pointer Learning (7 kinds of QT Smart pointers and 4 STD smart pointers)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.