I have been catching up on my c++ lately, after a couple years of exclusive Objective-C on iOS, and the topic that comes up most on 'new style' c++ is RAII
To make sure I understand RAII concept correctly, would you consider Objective-C lazy loading property accessors a type of RAII? For example, check the following access method
- (NSArray *)items {
if(_items==nil) {
_items=[[NSArray alloc] initWithCapacity:10];
}
return _items
}
Would this be considered an example of RAII? If not, can you please explain where I'm mistaken?
RAII is unfortunately widely misused.
The initial concept Resources Acquisition Is Initialization was all about using constructors to guarantee that thing occurred. In this idea:
std::fstream out("somefile.txt", "w");
should guarantee that if out
is ever created, then the file exists and is ready to be used.
Therefore, Lazy Loading is the opposite of RAII !
Note: nowadays, though, RAII is mostly used to refer to automatic cleanup. An example is smart pointers. It's a bit far from its initial goal.
Regarding cleanup, another idiom is SBRM for Scoped Bound Resources Management. It does not fully capture the idea of deterministic cleanup though. The idea of SBRM is that you guarantee that a resource will be cleaned when a certain object goes out of scope. This can be achieved through boost::scoped_ptr
for example.
However this fails to capture what a unique_ptr
does, since you can actually return
a unique_ptr
thus letting the resource escape the scope it was created in!