Introduction to RAII in C + +

Source: Internet
Author: User
Tags mutex

Summary

RAII technology is considered to be the best way to manage resources in C + +, further extending the use of RAII technology can also achieve a safe, concise state management, writing elegant and exceptionally safe code.

Resource Management

Raii is the inventor of C + + Bjarne Stroustrup proposed concept, RAII full name is "Resource acquisition is initialization", literal translation comes from "Resource acquisition is initialized", This means that the resource is allocated in the constructor, and the resources are freed in the destructor. Because the language mechanism of C + + guarantees that when an object is created, the constructor is called automatically, and the destructor is called automatically when the object goes out of scope. So, under the guidance of RAII, we should use classes to manage resources, binding resources and the life cycle of objects.

Smart pointers (Std::shared_ptr and Std::unique_ptr), RAII's most representative implementations, use smart pointers to automate memory management and no longer have to worry about forgetting the memory leaks caused by the delete. Without exaggeration, with smart pointers, there is little need for a delete in the code.

Memory is just one of the resources, and here we discuss the more generalized resource management. For example, the opening and closing of files, the acquisition and release of handles in Windows, and so on. According to the conventional RAII technology needs to write a bunch of management of their classes, sometimes it seems more troublesome. However, if you release manually, you will typically consider various exception handling, such as:

void function () {    *f = fopen ("test.txt"'r');     if  (.....)    {        fclose (f);         return ;    }     Else if (.....)    {        fclose (f);         return ;    }    Fclose (f);    ......}

Here is an introduction to the online implementation of the I think the more concise method, the article here. The author uses the lambda expression in the c++11 standard and the Std::function method, which is very concise and clear. Look directly at the code:

#defineScopeguard_linename_cat (name, line) name# #line#defineScopeguard_linename (name, line) scopeguard_linename_cat (name, line)#defineOn_scope_exit (callback) Scopeguard Scopeguard_linename (EXIT, __line__) (callback)classscopeguard{ Public:    ExplicitScopeguard (std::function<void() >f): Handle_exit_scope_ (f) {}; ~Scopeguard () {handle_exit_scope_ ();}Private: Std::function<void() >handle_exit_scope_;};intMain () {{A }*a =NewA (); On_scope_exit ([&] {DeleteA;});    ......    } {Std::ofstream F ("Test.txt"); On_scope_exit ([&] {f.close ();});    ......    } System ("Pause"); return 0;}

For ease of use, the author also defines a macro definition that names the Scopeguard type object according to the line number. See, when the Scopeguard object goes out of scope, Scopeguard's destructor calls the Handle_exit_scope_ function, which is the contents of the lambda expression, so fill in the LAMABDA expression with the code freed by the resource, How concise and clear. There is no need to write a separate management class for each resource management, nor do you need to consider manual release of the processing under various exceptions, while the application and release of resources are put together to write, never forget.

State management

RAII Another extended application is the ability to implement secure state management. A typical application is in thread synchronization, using Std::unique_lock or Std::lock_guard to mutex std:: Mutex for state management. Usually we don't write the following code:

Std::mutex mutex_; void function () {    mutex_. Lock ();    ......    ......    Mutex_.unlock ();}

Because the code between the mutex lock and the unlock is likely to have an exception, or there is a return statement, then the mutex will not be correctly unlock, causing the thread to deadlock. So the right way to do this is to use Std::unique_lock or Std::lock_guard for state management of mutexes:

Std::mutex mutex_; void function () {    std::lock_guardlock(mutex_);    ......    ......}

When the Std::lock_guard object is created, the Std::mutex object is lock, and when the Std::lock_guard object is out of scope, the object is automatically Std::mutex unlocked, so You don't have to worry about thread deadlocks caused by code exceptions.

Summarize

As can be seen from the above analysis, the core idea of RAII is to bind the resource or state to the life cycle of the object, and realize the security management of resources and State through the language mechanism of C + +. Understanding and using RAII can make software design clearer and code more robust.

Reference

1, http://mindhacks.cn/2012/08/27/modern-cpp-practices/

2, http://www.jellythink.com/archives/101

3, http://www.cppblog.com/aaxron/archive/2011/03/22/142475.html

Introduction to RAII in C + +

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.