Skip to content

Safer pointer type system

jckarter edited this page Nov 14, 2010 · 3 revisions

Motivation

Clay's library already implements SharedPointers, UniquePointers, and referenceTypes for safe resource management. However, at the primitive level, there is only one Pointer type, which shares many of the same undesirable traits of C/C++'s primitive pointer types, including support for wanton pointer arithmetic and lack of scope control. By separating the type of pointers (which don't support arithmetic) from contiguous sequence coordinates (i.e., pointers into arrays or vectors, which do support pointer arithmetic) and providing primitive support for scoped-restricted LocalPointers to local variables, which cannot be copied, moved, or assigned, would protect against common pointer programming errors while

Proposed implementation

Memory allocation functions, as well as taking the address of a global value, should return a Pointer[T] referencing the object, as now. However, Pointer[T] should not support add, subtract, inc, or dec operations. Operations that reference elements within arrays or vectors should return values of a separate ContiguousCoordinate[T] type. The binary representation for ContiguousCoordinate should be the same as for Pointer, but ContiguousCoordinate should support arithmetic as expected for a RandomAccessCoordinate.

The address of a local variable is never valid outside of its current scope, so applying the & operator to a local variable should return a value of a separate LocalPointer type. This type would also share the same binary representation as Pointer[T], but have additional restrictions: it may not be copy-constructed, moved, or assigned, similar to boost's scoped_ptr. However, unlike boost::scoped_ptr, LocalPointer should not destroy its referenced object, because the referenced value will be destroyed as a normal part of its lifecycle. The restrictions on ownership transfer will prevent common errors of pointers to local object. If ref=> lambdas capture their environment using LocalPointers behind the scenes, by-reference lambdas will likewise be guarded from improperly escaping upward of their original scope.

Of course, it's important to be able to escape the type system sometimes, so it should be possible to explicitly cast among Pointer, LocalPointer, and ContiguousCoordinate. Implicit conversion via the proposed convert operator can occur in the more restrictive direction (ContiguousCoordinate implicit-converts to Pointer implicit-converts to LocalPointer), but implicit conversion in the less restrictive direction should not be allowed.

Discussion

Please add comments here.

LocalPointer may complicate interfacing with C libraries that use Pointers for pass-by-reference and out parameters. For LocalPointer to be practical it has to remain convenient to pass pointers downward to C interfaces.

Clone this wiki locally