Why is RAII so named? [closed]

2020-02-28 06:42发布

问题:


Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 7 years ago.

The sense I get about this idiom is that it is useful because it ensures that resources are released after the object that uses them goes out of scope.

In other words, it's more about de-acquisition and de-initialisation, so why is this idiom named the way it is?

回答1:

First, I should note that it's widely considered a poorly named idiom. Many people prefer SBRM, which stands for Stack Bound Resource Management. Although I (grudgingly) go along with using "RAII" simply because it's widely known and used, I do think SBRM gives a much better description of the real intent.

Second, when RAII was new, it applied as much to the acquisition as releasing of resources. In particular, at the time it was fairly common to see initialization happen in two steps. You'd first define an object, and only afterwards dynamically allocate any resources associated with that object. Many style guides advocated this, largely because at that time (before C++ had exception handling) there was no good way to deal with failure in a constructor. Therefore, the style guides often said, constructors should do only the bare minimum of work, and specifically avoid anything that was open to failure -- especially allocating resources (and a few still say things like that).

Quite a few of those already handled releasing the resources in the destructor though, so that wouldn't have been as clear a distinction from previous practice.