C++11 Implementing RAII Features

Source: Internet
Author: User

Reference article 7911997

What is RAII technology? (see Baidu Encyclopedia related articles)

RAII (Resource acquisition is initialization) is a simple technique that uses the object lifecycle to program resources such as memory, file handles, network connections, mutexes, and so on.
The general practice of RAII is to get the resource when the object is constructed, and then to control access to the resource so that it remains valid for the lifetime of the object, and finally releases the resource when the object is refactored. In this, we actually managed to manage the responsibility of a resource to an object. There are two major benefits to this approach:

      • You do not need to explicitly release resources.
      • In this way, the resources required by the object remain valid for the duration of their life.

In a previous article, the implementation of a lock is compliant with RAII

Here's a way to implement exception security

Example 1. The following code

HANDLE h = CreateFile (...); CloseHandle (h);

If the first line has an exception, it will skip the CloseHandle directly, and the method described below is a simple and convenient way to prevent this from happening.

classscopeguard{ Public:    ExplicitScopeguard (std::function<void() >onexitscope): Onexitscope_ (Onexitscope), Dismissed_ (false)    { }    ~Scopeguard () {if(!dismissed_)        {Onexitscope_ (); }    }    voidDismiss () {dismissed_=true; }Private: Std::function<void() >Onexitscope_; BOOLDismissed_;Private://noncopyableScopeguard (ScopeguardConst&); Scopeguard&operator= (ScopeguardConst&);};

The use of this class is simple, you give it a std::function, it is responsible for the execution of the destruction, most of the time this function is a lambda, for example:

HANDLE h = CreateFile (...); Scopeguard OnExit ([&] {CloseHandle (h);});

OnExit faithfully executes CloseHandle at the time of the destruction. In order to avoid the trouble of naming the object (if there are multiple variables, the name is cumbersome), you can define a macro that mixes the line number into the variable names so that each defined Scopeguard object is uniquely named.

#define SCOPEGUARD_LINENAME_CAT (name, line) name# #line # define SCOPEGUARD_LINENAME (name, line) scopeguard_linename_ CAT (name, line) #define ON_SCOPE_EXIT (callback) Scopeguard Scopeguard_linename (EXIT, __line__) (callback)

The Dismiss () function is also part of the original design of Andrei, which is designed to support rollback mode, such as:

Scopeguard Onfailurerollback ([&] {/* rollback */}); ...//do something that could failonfailurerollback.dismiss ();

In the above code, the rollback logic will be executed whenever an exception is thrown anywhere in the "do something" process. If "Do something" succeeds, Onfailurerollback.dismiss () is called, setting Dismissed_ to TRUE to block the execution of rollback logic.

Scopeguard is a resource auto-release, and an indispensable facility for rollback in the case of code errors, c++98 is not only complex, but cumbersome to use because of the lack of lambda and tr1::function support, There are many traps, and the c++11 immediately becomes extremely simple, which becomes a daily facility. The RAII paradigm of C + + is considered to be the best paradigm for the release of resource certainty (the Using keyword of C # will be indented in the case of a nested resource request release, rather than scale), and with On_scope_exit, it is very convenient to apply for releasing resources in C + +.

Acquire Resource1on_scope_exit ([&] {/* release Resource1 */}) acquire Resource2on_scope_exit ([&] {/* release R ESOURCE2 */}) ...

The benefit of doing this is not only that the code does not appear needlessly indented, but that the resource request and the freed code are visually adjacent to each other and never forgotten. Not to mention that you just need to write the freed code in one place, and whatever happens, the scope exits and we don't have to worry about the resources being freed. I believe this paradigm will soon become the standard way for all C + + code to allocate and release resources, because this is one of the really good parts of the evolution of C + + over the decades.

C++11 Implementing RAII Features

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.