Pointers that automatically delete the underlying object.
The library makes extensive use of referencing counting smart pointers. It uses the following paradigm consistently for any class that intends to be reference counted.
- The class shall mark all of its normal C++ constructors as having protected access. This is to prevent users from allocating such objects statically or on the stack, yet allowing subclasses to use them.
- For each class their shall be defined a "Ptr" type which is the smart pointer type for the class. Class templates define this type as a public member; non-template classes may define it as a public member and/or in the same namespace as the class. In the latter case, the type name will be "Ptr" appended to the class name.
- The class shall have a static
instance
method corresponding to each C++ constructor. Each such class method takes the same arguments as one of the constructors, allocates and constructs and object with new
, and returns a Ptr
. These methods are usually public.
- The class shall have a public destructor only for the sake of the smart pointer.
- If a class hierarchy needs virtual constructors they shall be named
create
.
- If a class needs virtual copy constructors they shall be named
copy
.
- The class shall have a factory function corresponding to each public
instance
method.
- Factory functions shall have the same name as the class, but an initial lower-case letter.
A simple example:
class SomeClass {
int someData_;
protected:
SomeClass(): someData_(0) {}
explicit SomeClass(int n): someData_(n) {}
public:
static Ptr instance() {
return Ptr(new SomeClass);
}
static Ptr instance(int n) {
return Ptr(new SomeClass(n));
}
};
SomeClass::Ptr someClass() {
return SomeClass::instance();
}
SomeClass::Ptr someClass(int n) {
return SomeClass::instance(n);
}