Boost logo

Boost :

From: Matus Chochlik (chochlik_at_[hidden])
Date: 2008-02-11 10:22:20


NOTE: Code to be discussed can be found in the Boost Vault in
directory Memory/RawPtr, archive rawptr-draft-0.xx.zip (where
xx is the current version of the draft)

Shorter version:

A class raw_ptr as a replacement for plain void* [void pointer] is
suggested that does run-time typechecking in a similar way
as Boost.Any does but follows syntax of void* as much as possible.
Thus in the ideal case allowing find-replace substitution of void*
in code without introducing syntax errors.

A new cast type; raw_cast is suggested to replace static_cast
when casting from untyped to typed pointer

When a bad cast is detected (at run-time) a compile-time defined
policy (by default calling of abort()) is executed.

Longer version:

Even though the use of untyped pointers in cpp applications is discouraged
and can be usualy avoided by using templates or by other means,
(like Boost.Any) there are situations where an untyped pointer
''must be used'' or is the best option.

The disadvantages are obvious, by using the void* we are deprived
of all information about the type the pointer points to.
This can lead to hard to find, persistent bugs in larger programs.

However in many applications that resort to using untyped
pointers the code follows pattern shown by this pseudo-code:

typedef <some-type> T;
T* ptr_x = acquire_ptr_to<T>([argument-list]);
...
void* raw_ptr_x = ptr_x;
store(raw_ptr_x, key_to_x);
...
T* ptr_x_2 = static_cast<T*>(retrieve(key_to_x));
use(ptr_x_2);

i.e.:
1) Create or get a pointer to an instance
    of a known type.
2) Store or pass the address of the instance
    by the means of an untyped pointer.
3) Let the code logic to determine the correct type
    and cast the pointer back by the means of static_cast

Even if the logic behind points 1) 2) and 3) is consistent
subtle bugs can be introduced that may cause undefined
behavior or application crashes.

The proposed raw_ptr
class that does the typechecking in a similar way as
Boost.Any does and allows to detect bad casts from
void* to typed pointer and act accoding to a policy
defined at compile-time (i.e. throw an exception,
call abort(), do nothing, etc.)

The main difference between the proposed raw_ptr and
::boost::any is that raw_ptr tries to follow the syntactic
properties of void* as much as possible.

A new cast type, namely raw_cast<T>(x) is proposed
to replace static_cast, when casting from raw_ptr to
typed pointer.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk