C ++ object Resource Management

Source: Internet
Author: User

For the usage of C ++ object resource management, note-to-self + keynote + idiom case + cross-reference notes

Keyword: RAII, deleter, Two-stage Initialization, pimpl, Reference Counting (RC), Copy on Write (COW), Smart Pointer (SP)


Directory

C-Language Resource Management Method
RAII
Deleter
Two-stage Initialization
Pimpl
Reference Counting
Smart Pointer
Reference books
C-Language Resource Management Method ^
See [cpp lang] 14.4 Resource Management

E.g. Very Beginning

[Cpp]
Void copy_file (const char * src, const char * dst)
{
FILE * srcFile = fopen (src, "r ");
If (srcFile = NULL)
Goto _ RET;
 
FILE * dstFile = fopen (src, "w ");
If (dstFile = NULL)
Goto _ CLOSE_SRC;
 
// Read source file, and transform it's content.
If (HANDLE_FAILED)
Goto _ CLOSE_DST;
 
// End processing
_ CLOSE_DST:
Fclose (dstFile );
_ CLOSE_SRC:
Fclose (srcFile );
_ RET:
Return;
}
Introduce the basic requirements of Resource Management:

Release upon exit, Release before returning.
Resources are released in the reverse order of their acquisition.
Other resource release methods (not recommended ):

Do-while-break Type: Avoid the above goto type deformation.
Throw-catch: the built-in type of throw, usually int or char *, with low efficiency and messy code.
RAII ^
RAII (Resource Acquisition Is Initialization) Is called Initialization. It Is the mainstream technology and cornerstone of C ++ Resource management.

See [cpp lang] 14.4.1; [effect cpp] Item 13, 14; wiki: RAII
See Stack Unwinding Stack rollback, wiki: Call Stack

Note:

RAII classes require that their components (base classes and members) be RAII. For non-RAII components, You need to manually manage resources (Release in destructor), such:

Most stdlib classes are in the RAII format, such as iostream, string, and STL container.
Some Classes of MFC are in the RAII format, such as CWnd and CGdiObject.
The COM interface is not in the RAII format. You need to manually call the Release method, but it can be encapsulated by SP such as CComPtr To Make It RAII.
Do not let the Destructor throw an exception. For details, see [cpp lang] 14.4.7; [effect cpp] Item 8.

Sample:

Class File: Small encapsulation of FILE
Class ScopedBuf: scoped buffer class (Use vector and resize to expand buffer instead .)
Deleter ^
See [effect cpp] Item 14; [boost tutorial] 3.4.8

Deleter deleteer: If the resource is not limited to the memory allocation type, you must use a flexible and unified method to specify the resource release operation, for example, the second parameter of the constructor shared_ptr of TR1/Boost specifies deleter.

Sample:

A batch of deleters: You can configure Check (Check is released) and Zeroed (Release post zero). Release operations include delete, delete [], free, Release (COM), CloseHandle, fclose
Two-stage Initialization ^
See Two Stage Construction in C ++ versus Initializing Constructors, RAII in C ++, Google C ++ Style Guide: Doing Work in Constructors Chinese Translation

Two-stage Initialization/Construction (abbr. 2-stage init) Two-stage Initialization/Construction:

Stage 1: Call the constructor to initialize the Object Body.
Stage 2: Call the init method of the object and initialize the resources involved in the object. The init here is the form name, for example, fstream: open, auto_ptr: reset, CWnd :: create is the current name of init. CWnd: Create 2-stage is mandatory (MFC style), while fstream and auto_ptr can be init or constructor.
Why 2-stage init? Or what benefits it brings:

Reusable object Ontology

Object array initialization. Because no syntax is used to specify how to construct each unit when initializing an array (with the exception of POD, {} can be used to initialize each unit), the default constructor can only be used for initialization, call init to initialize each unit.

Alternative method: replace init with the placement new + construct. std: allocator: construct uses this method. For more information about placement new, see [effect cpp] Item 52; [meffect cpp] Item 8

How to describe the status of the object after initialization, such as reporting an error during initialization:

The init method can return values. Google C ++ Style tends to use this method: the constructor (init stage 1) only performs simple initialization, called trivial init. The truly meaningful non-trivial init is implemented in the init method. This is because the exception system is not recommended for Google C ++ Style.

Constructor usually throws an exception. I usually use this method instead of 2-stage init. I think 2-stage init fucked RAII. Of course, 2-stage init is preferred when initialization errors are expected to be high and there are a large number of objects in the efficiency-sensitive aspect during initialization.

Sets the state description variable in the object, applicable to constructors and init. It is not recommended to use method 3 to set object state variables unless the object itself has strong state-driven characteristics.

More about 2-stage init:

Public init vs. private init

Only public init is for the purpose of 2-stage init, while private init is another thing, most of it is to extract the public part of multiple overloaded constructors into an init function to reduce code

Init vs. re-init

When a user uses init, is the actual syntax re-init? That is, the execution process:

First, determine whether the object has allocated resources. If yes, release the object.
Apply for a new resource www.2cto.com
So: RAII makes resource management easier, while using 2-stage init makes things more complex.

Init vs. ctor

Consider the efficiency of the two methods (pseudo code ):

Use constructors:

[Cpp]
// D is the scoped object of for. In the following cases, d will be destroyed.
// 1. Conditional Exit 2. break exit
// 3. Each iteration ends 4. continue ends this iteration
For (int I = 0; I <NUM; I ++ ){
Data d (dataFile );
D. process ();
}
Use init:

[Cpp]
// Set init to re-init
Data d;
For (int I = 0; I <NUM; I ++ ){
D. init (dataFile );
D. process ();
}
Init is not cheap, but the version of the constructor can be made by using the constructor object construction method. For details, see [effect cpp] Item 26.

Pimpl ^
See [effect cpp] Item 14, 25, 29, 31

Pimpl (Pointer to Implementation) is essentially the separation of Implementation and Wrapper. Bjarne is used to calling Implementation a Representation)

Note:

Overhead:

Reduced Space Overhead: Only pimpl pointers
Time overhead increases: learn more about cited operations

Copy method:

Shallow Copy: only Copy pimpl pointers, such as standard SP: auto_ptr and cmd_ptr.
Deep copy enables wrapper to have Value Semantics and copy Semantics.

Deep Copy: Copy the object specified by pimpl
The shallow Copy enables wrapper to have Reference Semantics. To make the shallow Copy have the value Semantics, you can use the RC + COW (Copy on Write) Copy-on-Write method.

Reference Counting ^
See [effect cpp] Item 13, 14; [meffect cpp] Item 17, 29

Reference Counting (RC) Reference count

Generally, you do not need to write the RC class from scratch, as long as the class contains the components of the RC, such as using the javas_ptr member.

Sample:

Class Person: RC + COW simple example

Class String: changed from [cpp lang] 11.12 A String Class

Technology: pimpl, RC, COW, Proxy class. Proxy class is used to differentiate the Read and Write semantics of operator []: R-value Usage vs. L-value Usage. For details, see [meffect cpp] Item 17, 30

Function: string class example of value semantics, without templated CharType, CharTraits, and Allocator

Bjarne: That done, we can throw away our exercises and use the standard library string. (Ch.20)

Smart Pointer ^
See [cpp lang] 11.10 Dereferencing, 14.4.2 auto_ptr; [effect cpp] Item 13, 14, 15, 17, 18; [meffect cpp] Item 28; [boost tutorial] 3.1 ~ 3.7

Smart Pointer (SP) Smart Pointer is a Delegation of Raw Pointer mechanism, technically equivalent to RAII + pimpl + Ownership Semantics.

Common SP help (from stdlib/Boost/TR1 ):

_ Ptr vs. _ array suffix

Ptr managed single object (new), array managed object array (new [])
Array type has [] operations (the subscript range is not checked), no *,-> operations
Array type can be replaced by vector or ptr type + vector

Scoped type

Ownership: Monopolize exclusive and Noncopyable
Note: Elements of STL containers cannot be used for value semantics.

Auto type

Ownership: Transfer and Distructive Copy destructive Copy
Note: Elements of STL containers cannot be used for value semantics.

Shared type

Ownership: Share, and RCSP (Reference-Counting Smart Pointer) references a Counting Smart Pointer
Features: Support for deleter, Cross-DLL, and Raw Pointer access
Note: Cycles of References ring References

See make_shared in <boost/make_shared.hpp>.

Weak_ptr

Ownership: Observe observation
Features: pseudo SP, not used independently, but used with shared_ptr to solve the ring-like reference Problem
See shared_from_this in <boost/enable_shared_from_this.hpp>.

Intrusive_ptr

Features: The size is the same as raw pointer, and the existing rc mechanism of the hosted object (intrusive) is used)

CComPtr, CComQIPtr

The SP that hosts the COM interface in ATL is derived from CComPtrBase and automatically runs the COM reference count AddRef and Release
CComQIPtr uses the COM interface IID

Sample:

Class AutoPtr, AutoArr: Specifies the auto SP of deleter described above.

 


Extracted from Breaker logs

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.