Introduction to QT smart pointers

Source: Internet
Author: User

Introduction

Qt provides many smart pointers, including qpointer, qshareddatapointer, qsharedpointer, qweakpointer, and qscopedpointer.

Description

Qpointer (4.0) is outdated and can be replaced by qweakpointer. It is not thread-safe.

Qshareddatapointer (4.0) provides copy-on-write and shortest copies for data, and provides data line security

Full protection. (Note: It is thread-safe to provide thread security protection for data in combination with qshareddata.

Qsharedpointer (4.5) implements a strongly typed pointer to shared resources that can be referenced and counted. It is thread-safe. It has a feature similar to STD: auto_ptr, and the biggest difference is that it cannot transfer ownership while auto_ptr can.

Qweakpointer (4.5) implements a weak type pointer of shared resources for reference counting, Which is thread-safe.

Qscopedpointer (4.6) implements a strong type pointer for exclusive resources with non-reference count, which is thread-safe.

Strong pointer: Never give up the ownership of the resource to which it points.

Weak pointer: allows the outside world to release its resources so that it waives the ownership of the resources it points.

Details

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 assigned 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. Once the object's management right is obtained, you cannot retrieve it from it.

No matter whether qscopedpointer or STD: unique_ptr has a good name, it passes the clear information to the Code Viewer: This smart pointer can only be applied in this field, cannot be transferred. Because its Beibei machine and value assignment operations are both private, we can compare the objects of qobject and Its Derived classes.

Note: Because the Beibei machine is private and value-assignment-controlled, it also has the same "disadvantage" as auto_ptr-it cannot be used as an element of a container.

Qsharedpointer and STD: shared_ptr

The qsharedpointer and STD: shared_ptr actions are closest to the original pointer and are the "smart pointer" Most like pointers. Their application limitations are wider than previously mentioned.

Like qscopedpointer, qsharedpointer encapsulates the dynamic objects assigned by the new operator on the heap. However, qsharedpointer implements the reference of a counter-type smart pointer, which can be freely copied and assigned values, share it on random occasions. When there is no code application (the reference count is 0), it deletes the encapsulated dynamically assigned object. Shared_ptr can also be securely stored in a standard container, and makes up for the disadvantages of STD: auto_ptr and qscopedpointer that they cannot use pointers as container elements because of the transfer semantics.

The Management Mechanism of Boost: shared_ptr is not complicated, that is, reference counting is performed on the Managed Objects. When a boost: shared_ptr is added, the reference counting of the object is added; one more boost: shared_ptr reduces the reference count of this object by one. If the reference count of this object is 0, no pointer is managed on it, call Delete to release the memory occupied by it. (See instance 2)

Compared with the boost: scoped_ptr introduced earlier, boost: shared_ptr can share the ownership of objects, so there is basically no limit on the scope of use (there are still some rules to follow, as described below), it can also be used in STL containers. In addition, it is thread-safe, which is also very important in multi-threaded programs.

Rules for using boost: shared_ptr:

Avoid direct memory management operations on the objects managed by shared_ptr to avoid re-release of the objects.

Shared_ptr cannot automatically manage the memory of objects that are referenced cyclically (this is a common problem of other memory management methods for reference count ).

Do not construct a temporary shared_ptr as a function parameter.

The following code may cause memory leakage:

Void test ()

{

Foo (boost: shared_ptr <implementation> (new implementation (), g ());

}

Correct usage:

Void test ()

{

Boost: shared_ptr <implementation> Sp (new implementation ());

Foo (SP, g ());

}

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 for the common qsharedpointer. It is more like a helper of qsharedpointer (because it does not have a common pointer action, there is no heavy-load operator * and-> ). Its most popular use is to help qsharedpointer work, and observe the application of data like an observer who does not hesitate.

If the weak_ptr is used to prevent strong references from forming a ring.

In QT, qweakpointer has a special penalty for qobject and its derived class objects. It can be used as a replacement for qpointer

Qshareddatapointer

This is a convenient object provided for implementing implicit sharing (copy-on-write during write) for common qshareddata.

The classes in QT are all implicitly shared, 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>)
The rare data members we need are placed in the employeedata class derived from qshareddata.

Qexplicitlyshareddatapointer

This is a convenient object provided for the explicit sharing of common qshareddata.

Qexplicitlyshareddatapointer and qshareddatapointer are very similar. However, it disables the write replication 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 ");

}

During writing, the Replication Technique leads to: E1 and E2 have the same employee ID, but there is a different name. In contrast to our waiting, explicit sharing can solve this problem, which makes the employee itself more like a pointer.

Instance resolution

Instance 1

1 int main (INT argc, char * argv [])

2 {

3 qcoreapplication A (argc, argv );

4 // raw pointer

5 qstring * P = new qstring ("hello ");

6 // implements non-reference-counted strong pointer

7 qscopedpointer <qstring> pscopedpointer (New qstring ("scoped "));

8 // build error, can not be shared and reference-counted

9 // qscopedpointer <qstring> pscopedpointerpscopedpointer2 = pscopedpointer;

10 // implements reference-counted strong sharing of pointers

11 qsharedpointer <qstring> psmart (New qstring ("smart "));

12 qsharedpointer <qstring> psmart2;

13 psmart2 = qsharedpointer <qstring> (New qstring ("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 = new qtimer ();

21 qweakpointer <qtimer> pweakpointer = timer;

22 // weak pointer's resources can be deleted from outside world

23 Delete timer;

24 if (pweakpointer. isnull ())

25 {

26 qdebug () <"contained qobject has been deleted ";

27}

28}

Instance 2

# Include <string>

# Include <iostream>

# Include <boost/shared_ptr.hpp>

Class implementation

{

Public:

~ Implementation () {STD: cout <"destroying implementation \ n ";}

Void do_something () {STD: cout <"did something \ n ";}

};

Void test ()

{

Boost: shared_ptr <implementation> SP1 (new implementation ());

STD: cout <"the sample now has" <sp1.use _ count () <"references \ n ";

Boost: shared_ptr <implementation> SP2 = SP1;

STD: cout <"the sample now has" <sp2.use _ count () <"references \ n ";

Sp1.reset ();

STD: cout <"after reset SP1. the sample now has" <sp2.use _ count () <"references \ n ";

Sp2.reset ();

STD: cout <"after reset SP2. \ n ";

}

Void main ()

{

Test ();

}

The output result of this program is as follows:

The sample now has 1 References

The sample now has 2 references

After reset SP1. the sample now has 1 References

Destroying implementation

After reset SP2.

We can see that the boost: shared_ptr pointer SP1 and SP2 both have the permission to access the implementation object, and when both SP1 and SP2 release the ownership of this object, the memory of the managed object is automatically released. The shared object's access permissions also enable automatic management of its memory.

References

Http://mobile.51cto.com/symbian-272817.htm

Http://www.mysjtu.com/page/M0/S670/670782.html

Http://blog.csdn.net/lmh12506/article/details/8897015

Http://blog.csdn.net/txb70780533/article/details/5385516

Qt Assistant

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.