Smart pointer Memo 1

Source: Internet
Author: User

Http://blog.163.com/modingfa_002/blog/static/11092546620115895230167/

--------------------------------------------------

Qt smart point smart pointer

09:52:30| Category:
Qt-High-Level
| Tag:Pointer QT shared_ptr STD label
|Font Size Subscription

 

    1. Qpointer (4.0) is outdated and can be replaced by qweakpointer. It is not thread-safe.
    2. Qshareddatapointer (4.0 )--ProvidesCopy-on-write and shortest copyTo provide thread security protection for data (instead of pointing to data pointers. (Note: thread security protection for data should be combinedQshareddataIt is thread-safe.
    3. Qsharedpointer (4.5) -- implements a strongly typed pointer to shared resources that can be referenced and counted. It is thread-safe.
    4. Qweakpointer (4.5) -- implements a weak type pointer of shared resources that can be referenced and counted. It is thread-safe.
    5. Qscopedpointer (4.6) -- implements a strong type pointer for exclusive resources with non-reference count, which is thread-safe.

Strong pointer :InWith the ownership of the resource it points to, this ownership will never be waived. 

Weak pointer:InAllow the outside world to release its resources and give up the ownership of the resources it points. 

QsharedpointerWithSTD: auto_ptrSimilar features, but the biggest difference is that it cannot transfer ownershipAuto_ptrYes. In fact,Scoped_ptrNever be copied or assigned a value!

 

BelowCodeExample of qsharedpointer, qweakpointer, and qscopedpointer:

View plaincopy to clipboardprint?
  1. IntMain (IntArgc,Char* Argv [])
  2. {
  3. Qcoreapplication A (argc, argv );
  4. // Raw pointer
  5. Qstring * P =NewQstring ("Hello");
  6. // Implements non-reference-counted strong pointer
  7. Qscopedpointer <qstring> pscopedpointer (NewQstring ("Scoped"));
  8. // Build error, can not be shared and reference-counted
  9. // Qscopedpointer <qstring> pscopedpointer2 = pscopedpointer;
  10. // Implements reference-counted strong sharing of pointers
  11. Qsharedpointer <qstring> psmart (NewQstring ("Smart"));
  12. Qsharedpointer <qstring> psmart2;
  13. Psmart2 = qsharedpointer <qstring> (NewQstring ("Smart 2"));
  14. Qsharedpointer <qstring> psharedponinter;
  15. // Can be shared safely and reference-counted
  16. Psharedponinter = psmart;
  17. Qdebug () <* (psmart. Data ());
  18. Qdebug () <* (psmart2.data ());
  19. Qdebug () <* (psharedponinter. Data ());
  20. Qtimer * timer =NewQtimer ();
  21. Qweakpointer <qtimer> pweakpointer = timer;
  22. // Weak pointer's resources can be deleted from outside world
  23. DeleteTimer;
  24. If(Pweakpointer. isnull ())
  25. {
  26. Qdebug () <"Contained qobject has been deleted";
  27. }
  28. }

 

Getting startedProgram

# Include <qapplication>
# Include <qlabel>
Int main (INT argc, char * argv [])
{
Qapplication app (argc, argv );
Qlabel * label = new qlabel ("Hello dbzhang800! ");
Label-> show ();
Return app.exe C ();
}

In From the delete Statement of QT, we mentioned that the program has memory leakage (The Destructor is not called), and three solutions are provided at that time:

    • Allocate the label object to the stack instead of heap.
    • Set tag space QT: wa_deleteonclose for label

    • Call Delete to delete the label object allocated to heap through new.

Note:

    • To clearly observe the call of constructor and destructor, We Can subclass the qlabel and replace the preceding qlabel with the label.

      Class label: Public qlabel
    • {
    • Public: Label (const qstring & text, qwidget * parent = NULL): qlabel (text, parent) {qdebug ("from constructor ");}~ Label () {qdebug ("from destructor ");}
    • };

In this article, we will continue to consider this issue from the smart pointer perspective.

Smart pointer

To manage resources such as memory, C ++ programmers usually use the raiI (resource acquisition is initialization) mechanism: Apply for resources in the class constructor and then use, finally, release resources in the destructor.

Without smart pointers, the programmer must ensure that the new object can be deleted at the right time and write exception capture code everywhere to release resources, the smart pointer can call Delete to analyze the dynamically allocated objects on the stack when exiting the scope (whether the normal process leaves or the process leaves due to exceptions.

Let's look at the smart pointers of the QT family:

Smart pointer

 

Introduction

Qpointer

Features of the QT Object Model (1)
Note: resources managed by the agent are not deleted during structure analysis.

 

Qsharedpointer

With reference count

Qt4.5

Qweakpointer

 

Qt4.5

Qscopedpointer

 

Qt4.6

Qscopedarraypointer

Derived class of qscopedpointer

Qt4.6

Qshareddatapointer

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! "));

Based on your QT version and the degree of C ++ compiler support, you can choose:

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

How to translate? I am not sure. Keep your English.

    • The qpointer class is a template class that provides  Guarded pointers  To qobjects.

    • Use: A guarded pointer, qpointer <t>. The behavior is similar to that of a regular pointer T *.

    • Feature: when the object to which it points (T must be a qobject and its derived class) is destroyed, it is automatically set to null.
      • Note: The guarded object will not be automatically destroyed during structure analysis.
    • Purpose: This is useful when you need to save pointers to qobject objects owned by others.

Example

Qpointer <qlabel> label = new qlabel; label-> settext ("& Status:");... If (Label) label-> show ();

If you delete this object in the... section, the label will be set to null automatically, instead of a wild pointer hanging (dangling.

Qpointer is one of the core mechanisms of the QT object model. Note the differences with other smart pointers.

STD: auto_ptr

There is not much to say about this.

    • Multiple auto_ptr cannot point to the same object! (When auto_ptr is destroyed, it will automatically delete the object it points to, so that the object will be deleted multiple times)

      • During the operation by copying the constructor or value assignment, the copied data will automatically become null, And the copied pointer will obtain the unique ownership of the resource.
    • Smart pointers cannot point to arrays (because they call Delete instead of Delete []).
    • A smart pointer cannot be an element of a container class.

In C ++ 0x, auto_ptr is no longer recommended and should be replaced by three other smart pointers in the future.

Qscopedpointer and STD: unique_ptr

They should be the same in concept. The following are not distinguished:

This is a smart pointer similar to auto_ptr. It encapsulates the dynamic objects allocated by the new operator on the stack and ensures that the dynamically created objects can be correctly deleted at any time. However, its ownership is more strict and cannot be transferred. Once the object's management right is obtained, you cannot get it back from it.

N/A qscopedpointer or STD: unique_ptr all have a good name. It transmits a clear message to the reader of the Code: This smart pointer can only be used in this scope, do not want to be transferred. Because its copy construction and value assignment operations are both private, we can compare the objects of qobject and Its Derived classes.

Usage(Manual from QT ):

Consider the absence of smart pointers,

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

When we write the delete statement multiple times in the exception handling statement, a slight carelessness will lead to resource leakage. With smart pointers, we can simplify these Exception Handling statements:

Void myfunction (bool usesubclass) {qscopedpointer <myclass> P (usesubclass? New myclass (): New mysubclass); qscopedpointer <qiodevice> device (handsoverownership (); If (m_value> 3) return; process (device );}

In addition, the first example is the best scenario to use these two pointers (destroy the objects pointed to by the main function out of the scope ).

Note: Because the copy construction and value assignment operations are private, they also have the same "defect" as auto_ptr -- they cannot be used as elements of the container.

Qsharedpointer and STD: shared_ptr

Qsharedpointer and STD: shared_ptr act as the closest pointer to the original pointer. They are the "smart pointer" like pointers, and have a wider application scope than previously mentioned.

Like qscopedpointer, qsharedpointer encapsulates the dynamic objects allocated by the new operator on the stack. However, qsharedpointer implements the reference of a counter-type smart pointer, which can be freely copied and assigned values, share it in any place. When no code is used (the reference count is 0), it is used to delete the encapsulated dynamically allocated object. Shared_ptr can also be securely stored in the standard container and make up for the defects that STD: auto_ptr and qscopedpointer cannot use pointers as container elements because of the transfer semantics.

Qweakpointer and STD: weak_ptr

Qsharedpointer of the strong reference type is already very useful. Why do we need qweakpointer of the weak reference type?

qweakpointer is a smart pointer introduced in combination with qsharedpointer. It is more like a helper of qsharedpointer (because it does not have common pointer behavior, operator * and-> are not reloaded ). It helps qsharedpointer to observe resource usage like a bystander.

  • weak_ptr is mainly used to prevent strong references from forming loops. From msdn:

    • A cycle occurs when two or more resources controlled by shared_ptr objects hold mutually referencing shared_ptr objects. for example, a circular linked list with three elements has 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 will ever become zero, and the nodes in the cycle will not be freed. to eliminate the cycle, the last node N2 shoshould 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 when the program's last reference to the head node is destroyed the nodes in the list will also be destroyed.
  • In QT, qweakpointer has special processing for qobject and its derived class objects. It can be used as a substitute for qpointer.
    • In this case, qsharedpointer is not required.
    • Higher efficiency than qpointer
Qshareddatapointer

This is a convenient tool for implementing implicit sharing (copy-on-write during write) with qshareddata.

Many classes in QT use implicit sharing technology, such as qpixmap, qbytearray, qstring ,.... It is also very easy to implement implicit sharing for our own classes. For example, to implement an employee class:

    • Define an employee class that only contains one data member (qshareddatapointer <employeedata>)

    • All the data members we need are placed in the employeedata class derived from qshareddata.

For more information, see qshareddatapointer manual.

Qexplicitlyshareddatapointer

This is a convenient tool for implementing explicit sharing with qshareddata.

Qexplicitlyshareddatapointer is similar to qshareddatapointer, But it disables the copy-on-Write function. This makes the created object more like a pointer.

An example is followed by the preceding employee:

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

The replication technology at the time of writing results in that E1 and E2 have the same employee ID but different names. Unlike what we expect, explicit sharing can solve this problem, which makes the employee itself more like a pointer.

 

By the way, let's take a look at the three smart pointers in Google coding specifications:
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 be the best design, but try to rewrite with single owners 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 of smart pointer-tr1

    • [C ++ boost] competition for smart pointer standards: boost vs. Loki

    • http://www2.research.att.com /~ BS/c000000000xfaq.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

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.