[Next] [Prev] [Up] [Top]

7.0 Classes

Constructors


7.12.1 Avoid referencing global objects (GL)

Avoid referencing global objects in a class constructor to avoid initialization order problems. Note that this is not as much a problem for pointers to global objects since a NULL value can be tested.

7.12.2 H eap allocation requires other methods (R)

If the constructor does any heap allocation, you must provide definitions for constructor and destructor, and at least protected declarations for the remaining canonical methods. Failure to do so will result in memory leaks or crashes.

7.12.3 Prefer construction to assignment (GL)

When declaring and initializing class variables in one statement, the preferred form is using the constructor syntax rather than the "assignment" syntax. Some compilers do not perform the standard optimization of eliminating the temporary implicit in the latter.

Examples:

TString s = "hello, world"; // possible inefficiency

TString s ("hello, world"); // good

7.12.4 Prefer initializers to assignment (GL)

Initialize all data members using the initializer syntax rather than assignment. Any const data members must use this initialization form.

Example:

class X {

private:

int fCount;

TString fName;

public:

...

};

X :: X () : fCount(0)

{

// Bad. This should have been in the initializer list with

// fCount. This causes runtime inefficiency!

fName = "Hi";

}


No Title
[Next] [Prev] [Up] [Top]

Generated with CERN WebMaker

This site was grabbed using the TRIAL version of Grab-a-Site. This message does not appear on a licensed copy of Grab-a-Site.