Problem |
Double initialization - once to establish an object's
identity, and once to establish its value - results in redundant
or throw-away work.
|
Context |
Initialization and assignment have different semantics in most
high-level languages. Since high-level semantics in
C++ come by convention and judicious choice of language features,
the programmer must exercise discipline to take advantage of this
distinction.
|
Forces |
The compiler understands the distinction between initialization and
assignment only in small degree: it understands
that constructors do initialization, but it can't keep the programmer
from using assignment semantics even when initialization semantics are
called for. For example, consider:
PathName::PathName() { this->dirName = DEFAULT_DIR; this->baseName = ""; } Before the two assignments take place, the constructor already has gone through the work of initializing the strings to some value. That takes time, and the work is undone by the assignments.
|
Solution |
Initialize members directly, instead of initializing to a default value and then
immediately overwriting the value. Use initializer syntax:
PathName::PathName() : dirName(DEFAULT_DIR), baseName("") { } |
Resulting context |
This eliminates gratuitous constructor and
destructor calls for an object. Furthermore, exception handling
now works right.
|
[Source: James Coplien, "After all, we can't ignore efficiency", C++ Report, May 96, p69] |