<rant>
Pointers are evil!. Pointers are a dangerous programming construction, and widely abused in the C++ programming world. They often lead to obscure programming errors, and in particular to memory leaks, which are notoriously hard to debug. If there is an alternative method that encapsulates pointers, or avoids their use altogether, then that should be used. Unfortunately, pointers are vital to programming in C, and many of the practices are imported into C++.
</rant>
Whilst the above might be considered a little extreme, it is worthwhile listing what pointers are used for, and considering what alternatives there might be. In Classdesc, objects are usually assumed to have the following properties: default constructable, copyable, assignable and serialisable. All the simple traditional C data types except for pointers satisfy these properties. Compound types (structs and classes) whose members satisy these properties also satisfy them, with classdesc automagically extending the serialisability property.
&
makes
obsolete the use of pointers for returning values from function
subroutines, and improves type safety. Of course this use of
pointers is of no concern for serialisation.
vector<T>
.
T&
) is suitable, but is limited to being initialised
only at object construction time. Also, any reference loops will
cause serialisation to enter an infinite loop and crash. C++ offers
more possibilities in the form of “smart pointers”, that guarantee
destruction of the referenced object once the reference object goes
out of scope. The standard C++ library provides auto_ptr
, but
this is noncopyable, pretty much defeating the purpose of smart
pointers. The Boost library (http://www.boost.org) provides several
different sharable smart pointers, that can be used. Classdesc
provides its own concept, ref that
is a type of dynamic reference. It should be noted that linked
lists can be handled easily with standard library containers.
clone()
virtual method, which is also how this is done in
Java. EcoLab provides an PolyBase base class in Poly.h
which
provides an interface for cloning, and interfaces for serialisation
can be found in the PolyPack
, PolyXML
and
PolyJson
headers and a simple
runtime type identification system. To create a reference, the
smart, modern way to do this is via the shared_ptr
smart
pointer class, which is found in the TR1 library of your compiler,
or in Boost if your compiler does not do TR1.