Contents Up << >>
Are there any lint-like guidelines for C++?
Yes, there are some practices which are generally considered dangerous.
However none of these are universally "bad," since situations arise when
even the worst of these is needed:
- a class "Fred"s assignment operator should return "*this"
as an "Fred&" (allows chaining of assignments)
- a class with any virtual fns ought to have a virtual destructor
- a class with a destructor, or an assignment operator, or a copy
constructor generally needs all three
- 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&)".
- always use initialization lists for class sub-objects rather than
assignment
the performance difference for user-defined classes can be substantial
(3x!)
- many assignment operators should start by testing if "we" are
"them"; e.g.,
Fred& Fred::operator= (const Fred& fred)
{
if (this == &fred) return *this;
//...normal assignment duties...
return *this;
}
Sometimes there is no need to check, but these situations generally
correspond to when there's no need for an explicit user-specified
assignment op (as opposed to a compiler-synthesized assignment-op).
- in classes that define both "+=," "+" and "=,"
"a+=b" and "a=a+b" should generally do the same thing;
ditto for the other identities of builtin types (e.g., a+=1 and
++a; p[i] and *(p+i); etc). This can be enforced by writing
the binary ops 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 ops don't even need to be friends.
But
it is sometimes possible to more efficiently implement common ops (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).
Keys for Smalltalk programmers to learn C++