An Overture to C Programmers
li
template
T add(T x, T y, T z) {
u
return x + y + z;
}
int main() {
auto a = add(1, 2, 3); // a is an int
auto b = add(1L, 2L, 3L); // b is a long
auto c = add(1.F, 2.F, 3.F); // c is a float
}
Listing 20: Using templates to create a generic
add
function
When you declare
add
u
, you don’t need to know
T
. You only need to know
that all the arguments and the return value are of type
T
and that
T
is addable.
When the compiler encounters
add
being called, it deduces
T
and generates a
bespoke function on your behalf. That’s some serious code reuse!
Class Invariants and Resource Management
Perhaps the single greatest innovation C++ brings to system programming
is the object life cycle. This concept has its roots in C, where objects have dif-
ferent storage durations depending on how you declare them in your code.
C++ builds on top of this memory management model with construc-
tors and destructors. These special functions are methods that belong to
user-defined types. User-defined types are the basic building blocks of C++
applications. Think of them as
struct
objects that can also have functions.
An object’s constructor is called just after its storage duration begins,
and the destructor is called just before its storage duration ends. Both the
constructor and destructor are functions with no return type and the same
name as the enclosing class. To declare a destructor, add a
~
to the begin-
ning of the class name, as Listing 21 illustrates.
#include
struct Hal {
Hal() : version{ 9000 } { // Constructor
u
printf("I'm completely operational.\n");
}
~Hal() { // Destructor
v
printf("Stop, Dave.\n");
}
const int version;
};
Listing 21: A
Hal
class containing a constructor and a destructor
The first method in
Hal
is the constructor
u
. It sets up the
Hal
object and
establishes its class invariants. Invariants are features of a class that don’t
change once they’ve been constructed. With some help from the compiler
and the runtime, the programmer decides what the invariants of a class
are and ensures that their code enforces them. In this case, the constructor
lii
An Overture to C Programmers
sets the
version
, which is an invariant, to
9000
. The
destructor is the second
method
v
. Whenever
Hal
is about to be deallocated, it prints
"Stop, Dave."
to the console. (Getting
Hal
to sing “Daisy Bell” is
left as an exercise to the
reader.)
The compiler makes sure the constructor and destructor are invoked
automatically for objects with static, local, and thread local storage dura-
tion. For objects with dynamic storage duration, you use the keywords
new
and
delete
to
replace
malloc
and
free
, Listing 22 illustrates.
#include
struct Hal {
Dostları ilə paylaş: