A Type-safe Generic Pointer

If you find this article contains errors or problems rendering it unreadable (missing images or files, mangled code, improper text formatting, etc) please contact the editor so corrections can be made. Thank you for helping us improve this resource

Introduction Sometimes there comes the need to store a pointer to an object whose type is not known at compile-time. The common method to achieve this in C++ is to store it in a void pointer. The void pointer can then be cast back to the appropriate type and used when required. Call-back functions[1] in libraries are a well-known example of this method; the user-data pointer is often a void pointer. This works, but has a glaring problem: it’s not type-safe; it’s up to the programmer to interpret the void pointer in the appropriate manner. Although programmers are quite used to taking care when dealing with void pointers, every once in a while a void pointer gets accidently cast to the wrong type of object. When this happens, the programmer is actually considered lucky if a crash occurs.

Enter any_ptr The any_ptr smart pointer[2] can point to any type of object and provide type-safe access to it. In some sense, any_ptr is to pointers what boost::any[3] is to objects. There are no requirements to be fulfilled by the types of objects that any_ptr can point to. In fact, the performance and size penalty incurred by its use is so low, that it could potentially be used almost wherever a void pointer is required. To start using any_ptr, we simply add a single header any_ptr.h (see source code accompanying this article) to our project. any_ptr has no dependencies on any library and can be used independently. any_ptr also does not require exceptions[5] or RTTI[6] to be enabled.

Although this should never really be an issue, an any_ptr occupies more space than a raw void pointer (its size is a void pointer plus an integer).

Casting from an any_ptr is slower than casting from a void pointer. Again this should never really be an issue.

Casting to base class pointers from an any_ptr will not work. This was pointed out to me by the thorough GameDev.net review staff.

Closing The any_ptr source code is released under the MIT license and has been tested on the following compilers:

Microsoft Visual C++ 2005/2008/2010

gcc 4.4.1 (TDM-2 mingw32)

There is much potential for improvement; if you make changes to the code, improve it, or have some better ideas, I would love to know. I can be reached by email at francisxavierjp [at] gmail [dot] com. Comments and suggestions are always welcome! References