Tuesday, December 06, 2005

Cline's Commandments

* A class Fred's assignment operator should return *this as a Fred& (allows
chaining of assignments)
* A class with any virtual[20] functions ought to have a virtual
destructor[20.4]
* A class with any of {destructor, assignment operator, copy constructor}
generally needs all 3
* A class Fred's copy constructor and assignment operator should have const in
the parameter: respectively Fred::Fred(const Fred&) and
Fred& Fred::operator= (const Fred&)
* When initializing an object's member objects in the constructor, always use
initialization lists rather than assignment. The performance difference for
user-defined classes can be substantial (3x!)
* Assignment operators should make sure that self assignment[12.1] does
nothing, otherwise you may have a disaster[12.2]. In some cases, this may
require you to add an explicit test to your assignment operators[12.3].
* In classes that define both += and +, a += b and a = a + b should generally
do the same thing; ditto for the other identities of built-in types (e.g.,
a += 1 and ++a; p[i] and *(p+i); etc). This can be enforced by writing the
binary operations using the op= forms. E.g.,

Fred operator+ (const Fred& a, const Fred& b)
{
Fred ans = a;
ans += b;
return ans;
}


This way the "constructive" binary operators don't even need to be
friends[14]. But it is sometimes possible to more efficiently implement common
operations (e.g., if class Fred is actually String, and += has to
reallocate/copy string memory, it may be better to know the eventual length
from the beginning).

No comments: