C ++ object Resource Management

Source: Internet
Author: User

Original link http://blog.csdn.net/breakerzy/article/details/7593137

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

  1. VoidCopy_file (Const Char* SRC,Const Char* DST)
  2. {
  3. File* Srcfile = fopen (SRC,"R");
  4. If(Srcfile = NULL)
  5. Goto_ Ret;
  6. File* Dstfile = fopen (SRC,"W");
  7. If(Dstfile = NULL)
  8. Goto_ Close_src;
  9. // Read source file, and transform it's content.
  10. If(Handle_failed)
  11. Goto_ Close_dst;
  12. // End Processing
  13. _ Close_dst:
  14. Fclose (dstfile );
  15. _ Close_src:
  16. Fclose (srcfile );
  17. _ RET:
  18. Return;
  19. }

Introduce the basic requirements of resource management:

    1. Release upon exit, release before returning.
    2. Resources are released in the reverse order of their acquisition.

Other resource release methods (not recommended ):

    1. Do-while-Break Type: Avoid the above goto type deformation.
    2. Throw-catch: the built-in type of throw, usually int, char *, which is less efficient and,CodeChaos
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:

    1. 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.
    2. 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:

    1. Stage 1: Call the constructor to initialize the Object Body.
    2. 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:

    1. Reusable object Ontology

    2. 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

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

      1. 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.

      2. 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.

      3. 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:

  1. 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

  2. Init vs. Re-init

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

    1. First, determine whether the object has allocated resources. If yes, release the object.
    2. Apply for new resources

    So: raiI makes resource management easier, while using 2-stage init makes things more complex.

  3. Init vs. ctor

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

    1. Use constructor:

      1. // D is a scoped object, in the following cases, D is destroyed.
      2. // 1. conditional Exit 2. break exit
      3. // 3. end of each iteration 4. continue ends this iteration
      4. for ( int I = 0; I
      5. data D (datafile);
      6. D. Process ();
      7. }
    2. Use init:

      1. // Set init to re-init
      2. Data D;
      3. For(IntI = 0; I <num; I ++ ){
      4. D. INIT (datafile );
      5. D. Process ();
      6. }

    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:

    1. Overhead:

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

    2. COPY method:

      1. Shallow copy: only copy pimpl pointers, such as standard SP: auto_ptr and cmd_ptr.
        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.

      2. Deep copy: copy the object specified by pimpl
        Deep copy enables wrapper to have value semantics and copy semantics.

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 ):

    1. _ PTR. _ array suffix

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

    2. scoped

      ownership: monopolize exclusive and noncopyable
      note: elements of STL containers that cannot be used for value semantics

    3. auto

      ownership: transfer Transfer and distructive copy destructive copy
      note: elements of STL containers that cannot be used for value semantics

    4. shared type

      ownership: Share share, and rcsp (reference-counting smart pointer) references a counting smart pointer.
      features: supports deleter, cross-DLL, and raw pointer access.
      note: cycles of references ring references

      For more information, see make_shared in

    5. weak_ptr

      ownership: Observe observation
      features: pseudo sp, not used independently, instead, use shared_ptr to solve the ring reference problem

      see shared_from_this in

    6. intrusive_ptr

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

    7. ccomptr, ccomqiptr

      SP hosting the COM interface in ATL are derived from ccomptrbase, and the com reference count addref and release are automatically executed. Ccomqiptr uses QueryInterface (QI) to query and obtain the COM interface based on the specified IID.

Sample:

    • Class autoptr, autoarr: Specifies the auto SP of deleter described above.
Reference books ^
      • [CPP Lang] "C ++ programming language, special ed", Bjarne stroustrup
      • [Effect CPP] "valid tive C ++, 3ed", Scott Meyers
      • [Meffect CPP] "more effective tive C ++", Scott Meyers
      • [Boost tutorial] boostProgramFull Library Development Guide, Luo Jianfeng

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.