Writing correct Cplusplus

From Apache OpenOffice Wiki
Jump to: navigation, search

C++ is an extremely complex language, and it is easy to accidentially write code that does not conform to The Standard. What is worse, there are cases where some compilers will not complain about your conformance violations, so that broken source code creeps into our code base. Only when someone later uses a pickier compiler will the error be noticed. (That is what just happened when trying to compile our code base with GCC 4.1, which is pickier than any of the compilers routinely used on the standard platforms until now.)

The following is a list of some issues you should have in mind when writing C++ code:

Extra Qualification

When declaring a member m of a class C, do not qualify m as C::m. That is, write

class C { void m(); };

and not

class C { void C::m(); };

This applies to namespaces as well. Write

namespace N { void f() {} }

and not

namespace N { void N::f() {} }

Friend Visibility

When declaring a friend f of a class C, f is injected into the surrounding namespace, but not visible in the surrounding namespace:

class C { friend void f(); };
void g() { f(); } // error

Declare f in the surrounding namespace, so that it is visible as intended:

void f();
class C { friend void f(); };
void g() { f(); } // ok

Escape Sequences

Only use valid escape sequences in character and string literals. For example, write


and not



Don't use trigraphs, especially not in literal character sequences. On some compiler platforms trigraphs have to be explicitly enabled, other platforms silently accept trigraphs without informing you. Using trigraphs in literal strings almost certainly does not what you expect. Avoid sequences with two question marks and a third character ??x, if you need them literally, escape the question marks.

const char a[] = "??/?";    // bad
const char a[] = "\?\?/?";  // OK

See also



Personal tools