Document Number:  N3677
Date:  2013-04-26
Project:  Programming Language C++, Library Working Group
Reply-to: Andrew L. Sandoval <sandoval at netwaysglobal dot com>

A Proposal to Add additional RAII Wrappers to the Standard Library

I. Table of Contents

II. Introduction

This proposal seeks to add generic RAII wrappers to the standard library. These wrappers will be used to manage the lifetime of various types of resources and to guarantee the execution of code blocks on scope exit. It builds on the concept of smart pointers like unique_ptr, but is designed for use with any type of resource that requires clean-up prior to scope exit, as well as any block of code (via lambda or function invocation) that needs to executed prior to scope exit.

III. Motivation and Scope

Quality C++ code requires the use of RAII to manage all types of resources in order to prevent leakage as well as to limit resource lifetime.  Resource leakage can occur from the obvious, though often overlooked, failure to clean-up a resource at its intended end-of-life, as well as the less obvious and arguably more common failure to ensure proper handling of resources during exception unwinding.

Smart pointers such as unique_ptr and shared_ptr provide an excellent means of managing the lifetime of pointer types. Many other RAII classes have been written to manage the lifetime and limit the scope of locks, such as Boost's boost::lock_guard. All of these and the many other types of RAII objects help to substantially improve C++ code quality. This proposal seeks to add a set of generic, light-weight RAII wrappers intended to manage the scope and lifetime of any other type of resource.  It also proposes an RAII wrapper intended to wrap a function, lambda, or functor which needs to execute prior to scope exit.

There are many types of resources that may not justify encapsulation in a broader object -- when a simple RAII wrapper around the resource will suffice or will provide a more obvious implementation. This is especially true when object re-use is not expected. In addition, RAII wrappers will simplify the design of objects that do encapsulate resources, allowing the generation of, or the declaration of the resource, to also declare its method of clean-up.  This results in moving resource clean-up outside of an explicit destructor, which also assures proper order of destruction when initialization order is correct.  This is common practice with pointers managed by unique_ptr and shared_ptr, and even with buffers allocated and managed by vector.

This proposal requests the addition of the following RAII wrapper types: