What is meant by Resource Acquisition is Initialization (RAII)?

前端 未结 8 1921
面向向阳花
面向向阳花 2020-11-21 04:23

What is meant by Resource Acquisition is Initialization (RAII)?

8条回答
  •  佛祖请我去吃肉
    2020-11-21 05:07

    This is a programming idiom which briefly means that you

    • encapsulate a resource into a class (whose constructor usually - but not necessarily** - acquires the resource, and its destructor always releases it)
    • use the resource via a local instance of the class*
    • the resource is automatically freed when the object gets out of scope

    This guarantees that whatever happens while the resource is in use, it will eventually get freed (whether due to normal return, destruction of the containing object, or an exception thrown).

    It is a widely used good practice in C++, because apart from being a safe way to deal with resources, it also makes your code much cleaner as you don't need to mix error handling code with the main functionality.

    * Update: "local" may mean a local variable, or a nonstatic member variable of a class. In the latter case the member variable is initialized and destroyed with its owner object.

    ** Update2: as @sbi pointed out, the resource - although often is allocated inside the constructor - may also be allocated outside and passed in as a parameter.

提交回复
热议问题