Objective C ++ Resource Management Summary

Source: Internet
Author: User


I found that the first time I read a book, I cannot clearly understand the nature of the problem. We still need to go back and summarize it. Therefore, I decided to write a summary for each part of the book in the future, on the one hand, you can organize your own knowledge, and on the other hand, you can easily compare ideas later.
Resource management
Preface
Resource leaks are common in programs. This chapter mainly tells us how to eliminate resource management problems. It is worth noting that resources here refer not only to dynamic memory allocation, other common resources include database connections, network sockets, and mutex locks. After using these resources, we must return them to the system. This problem occurs especially when exceptions occur and programmers maintain the software.

Clause 13: object-oriented resource management
First look at the code segment:
[Cpp]
Void test ()
{
Int * t = new int; // obtain the resource
...
Delete t; // release resources
}


If an exception occurs in "..." or return exists, the resource may be leaked. Maybe you will say, I am very careful, I will not let your code have this problem. Well, if this is a project, this Code may be modified by the maintenance personnel, and he may add an exception or return in. Maybe you will say that you will write the notes for this code into the document, however, I think we should regard ourselves as "customers" (Here we refer to the people who use this code and maintain the Code). We need to think for ourselves. If we can do well, you shouldn't leave the trouble to others.
To prevent the above phenomenon, we can put the resource into the object and rely on the "Automatic calling mechanism of destructor" of c ++ to ensure that the resource is released.
[Cpp]
Void test
{
Auto_ptr <int> t (new int); // pay attention to the initialization method.
...
} // Automatic delete t of the destructor of auto_ptr
Auto_ptr is a pointer-only function. The Destructor automatically calls delete for the object.
We recommend that you use auto_ptr and shared_ptr in the book (I will not introduce this here. If you are interested, You can google it yourself). However, you can also write resource management classes by yourself, but it involves the details that need to be considered, the terms will be discussed later.

Clause 14: copying actions in resource management
As mentioned in the previous terms, sometimes auto_ptr is not suitable for resource management. We need to create resource management classes by ourselves.
[Cpp]
Void lock (Mutex * pm); // lock the Mutex referred to by the pm
Void unlock (Mutex * pm); // lock the Mutex
Class Lock
{
Public:
Explicit Lock (Mutex * pm): mutexPtr (pm)
{
Lock (mutexPtr); // obtain resources
}
~ Lock ()
{
Unlock (mutexPtr); // release resources
}
Private:
Mutex * mutexPtr;
};
As shown above, we will automatically release resources for Mutex, but one problem we need to consider is what will happen if the Lock is replicated?

Lock m1 (& m); // Lock
Lock m2 (m1); // copy
The consequence is that the same resource will be released twice.

How can we choose to solve this problem:
1. Prohibit Replication
When a resource management class object is copied, if it is unreasonable, we will choose to disable replication. You can declare the copying operation as private without implementing it to prohibit it. (Detailed in Clause 6)
2. Sacrifice the reference counting method for underlying resources"
Use a variable to save the number of references. If the number of references is 0, it is destroyed. This is the shared_ptr practice (In addition, shared_ptr allows you to specify the deleteer. When the number of references is 0, the deleteer will be called)
3. Copy the bottom Resource
That is, "deep copy" will not only produce a replica for the pointer, but also create a new memory.
4. transfer the ownership of the bottom Resource
Simply put, ownership is transferred from the Copied object to the Copied object, and the Copied object loses ownership. This is implemented by auto_ptr.
For example
[Cpp
Auto_ptr <int> t (new int );
Auto_ptr <int> a = t; // The ownership changes from t to a, and t will point to NULL.

Clause 15: Provide access to original resources in resource management
One problem we need to face is that many API parameters directly involve resources, and we place resources in resource management. Therefore, we need to provide access to the original resources.
[Cpp]
Auto_ptr <int> t (new int );
Int test (int * t); // directly involves resources
[Cpp] view plaincopy
<Pre> </pre> <span style = "font-size: 18px"> <span style = "font-family: Microsoft YaHei"> </span>
<Pre> </pre>
<Pre> </pre>
<Pre> </pre>
<Pre> </pre>
<Pre> </pre>
There are two ways to achieve the goal: Display conversion and implicit conversion.
1. Display Conversion
Generally, a get () member function is provided to return resources. This is what auto_ptr and shared_ptr do.
But the consequence of doing so is frequent use of get ().
2. implicit conversion
Provides implicit conversion functions
[Cpp]
Class Font {
 
Public:
 
...
 
Operator FontHandle () const {return f;} // function for implicit conversion
...
 
};
However, errors may increase:
[Cpp]
<Pre> </pre>
<Pre> </pre>
<Pre> </pre>
<Pre> </pre>
<Pre> </pre>
FontHandle f2 = f1; // f1 is a Font object
I just wanted to copy a Font, but I accidentally wrote it as FontHandle. At this time, f2 will be implicitly converted to FontHandle and then copied.

My personal opinion is to select a method as needed.

Clause 16: use the same form in pairs of new and delete
There is nothing to say. Simply put, if you use [] in the new expression, you must also use [] in the corresponding delete expression. If you do not use [] in the new expression, do not use [] in the corresponding delete expression.
Note that when typedef is used,
[Cpp]
Typedef std: string AddressLines [4];
Std: string * pal = new AddressLines; // note that "new AddressLines" returns a string *, just like "new string [4 ]".
Delete pal; // The behavior is undefined.
Delete [] pal; // very good

Clause 17: place a new object into a smart pointer using an independent statement
[Cpp]
ProcessWidget (std: tr1: shared_ptr <Widget> pw (new Widget), int priority );
May cause resource leakage. Why?
Because of word order problems!
This statement completes three tasks in total:
Call priority.
Run "new Widget ".
Call the constructor tr1: shared_ptr.
Their operation order is elastic. If they are executed in the following order:
1. Execute "new Widget ".

2. Call priority.

3. Call the constructor tr1: shared_ptr.

[Cpp]
Std: tr1: shared_ptr <Widget> pw (new Widget); // create a Widget in a separate statement
// And store a smart pointer
ProcessWidget (pw, priority (); // the call will not be leaked. ,

Summary: This chapter is over. I have learned a lot. I found that in the summary process, I can convert the author's words and get something to write in the future.
 

Related Article

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.