Skip to main content

Make sure base classes have virtual destructors.

Item 14: Make sure base classes have virtual destructors.
Sometimes it's convenient for a class to keep track of how many objects of its type exist. The straightforward
way to do this is to create a static class member for counting the objects. The member is initialized to 0, is
incremented in the class constructors, and is decremented in the class destructor. (Item M26 shows how to
package this approach so it's easy to add to any class, and my article on counting objects describes additional
refinements to the technique.)
You might envision a military application, in which a class representing enemy targets might look something like
this:
class EnemyTarget {
public:
EnemyTarget() { ++numTargets; }
EnemyTarget(const EnemyTarget&) { ++numTargets; }
~EnemyTarget() { --numTargets; }
static size_t numberOfTargets()
{ return numTargets; }
virtual bool destroy();
// returns success of
// attempt to destroy
// EnemyTarget object
private:
static size_t numTargets;
// object counter
};
// class statics must be defined outside the class;
// initialization is to 0 by default
size_t EnemyTarget::numTargets;
This class is unlikely to win you a government defense contract, but it will suffice for our purposes here, which
are substantially less demanding than are those of the Department of Defense. Or so we may hope.
Let us suppose that a particular kind of enemy target is an enemy tank, which you model, naturally enough (see
Item 35, but also see Item M33), as a publicly derived class of EnemyTarget. Because you are interested in the
total number of enemy tanks as well as the total number of enemy targets, you'll pull the same trick with the
derived class that you did with the base class:
class EnemyTank: public EnemyTarget {
public:
EnemyTank() { ++numTanks; }
EnemyTank(const EnemyTank& rhs)
: EnemyTarget(rhs)
{ ++numTanks; }
~EnemyTank() { --numTanks; }
static size_t numberOfTanks()
{ return numTanks; }
virtual bool destroy();
private:
static size_t numTanks;
};
// object counter for tanks
Having now added this code to two different classes, you may be in a better position to appreciate Item M26's
general solution to the problem.
Finally, let's assume that somewhere in your application, you dynamically create an EnemyTank object using
new, which you later get rid of via delete:
EnemyTarget *targetPtr = new EnemyTank;
...
delete targetPtr;
Everything you've done so far seems completely kosher. Both classes undo in the destructor what they did in the
constructor, and there's certainly nothing wrong with your application, in which you were careful to use delete
after you were done with the object you conjured up with new. Nevertheless, there is something very troubling
here. Your program's behavior is undefined ? you have no way of knowing what will happen.
The °C++ language standard is unusually clear on this topic. When you try to delete a derived class object
through a base class pointer and the base class has a nonvirtual destructor (as EnemyTarget does), the results are
undefined. That means compilers may generate code to do whatever they like: reformat your disk, send
suggestive mail to your boss, fax source code to your competitors, whatever. (What often happens at runtime is
that the derived class's destructor is never called. In this example, that would mean your count of EnemyTanks
would not be adjusted when targetPtr was deleted. Your count of enemy tanks would thus be wrong, a rather
disturbing prospect to combatants dependent on accurate battlefield information.)
To avoid this problem, you have only to make the EnemyTarget destructor virtual. Declaring the destructor
virtual ensures well-defined behavior that does precisely what you want: both EnemyTank's and EnemyTarget's
destructors will be called before the memory holding the object is deallocated.
Now, the EnemyTarget class contains a virtual function, which is generally the case with base classes. After all,
the purpose of virtual functions is to allow customization of behavior in derived classes (see Item 36), so almost
all base classes contain virtual functions.
If a class does not contain any virtual functions, that is often an indication that it is not meant to be used as a
base class. When a class is not intended to be used as a base class, making the destructor virtual is usually a bad
idea. Consider this example, based on a discussion in the ARM (see Item 50):
// class for representing 2D points
class Point {
public:
Point(short int xCoord, short int yCoord);
~Point();
private:
short int x, y;
};
If a short int occupies 16 bits, a Point object can fit into a 32-bit register. Furthermore, a Point object can be
passed as a 32-bit quantity to functions written in other languages such as C or FORTRAN. If Point's destructor
is made virtual, however, the situation changes.
The implementation of virtual functions requires that objects carry around with them some additional
information that can be used at runtime to determine which virtual functions should be invoked on the object. In
most compilers, this extra information takes the form of a pointer called a vptr ("virtual table pointer"). The vptr
points to an array of function pointers called a vtbl ("virtual table"); each class with virtual functions has an
associated vtbl. When a virtual function is invoked on an object, the actual function called is determined by
following the object's vptr to a vtbl and then looking up the appropriate function pointer in the vtbl.
The details of how virtual functions are implemented are unimportant (though, if you're curious, you can read
about them in Item M24). What is important is that if the Point class contains a virtual function, objects of that
type will implicitly double in size, from two 16-bit shorts to two 16-bit shorts plus a 32-bit vptr! No longer will
Point objects fit in a 32-bit register. Furthermore, Point objects in C++ no longer look like the same structure
declared in another language such as C, because their foreign language counterparts will lack the vptr. As a
result, it is no longer possible to pass Points to and from functions written in other languages unless you
explicitly compensate for the vptr, which is itself an implementation detail and hence unportable.
The bottom line is that gratuitously declaring all destructors virtual is just as wrong as never declaring them
virtual. In fact, many people summarize the situation this way: declare a virtual destructor in a class if and only
if that class contains at least one virtual function.
This is a good rule, one that works most of the time, but unfortunately, it is possible to get bitten by the
nonvirtual destructor problem even in the absence of virtual functions. For example, Item 13 considers a class
template for implementing arrays with client-defined bounds. Suppose you decide (in spite of the advice in Item
M33) to write a template for derived classes representing named arrays, i.e., classes where every array has a
name:
template
// base class template
class Array {
// (from Item 13)
public:
Array(int lowBound, int highBound);
~Array();
private:
vector data;
size_t size;
int lBound, hBound;
};
template
class NamedArray: public Array {
public:
NamedArray(int lowBound, int highBound, const string& name);
...
private:
string arrayName;
};
If anywhere in an application you somehow convert a pointer-to-NamedArray into a pointer-to-Array and you
then use delete on the Array pointer, you are instantly transported to the realm of undefined behavior:
NamedArray *pna =
new NamedArray(10, 20, "Impending Doom");
Array *pa;
...
pa = pna;
// NamedArray* -> Array*
...
delete pa;
// undefined! (Insert theme to
//°Twilight Zone here); in practice,
// pa->arrayName will often be leaked,
// because the NamedArray part of
// *pa will never be destroyed
This situation can arise more frequently than you might imagine, because it's not uncommon to want to take an
existing class that does something, Array in this case, and derive from it a class that does all the same things,
plus more. NamedArray doesn't redefine any of the behavior of Array ? it inherits all its functions without
change ? it just adds some additional capabilities. Yet the nonvirtual destructor problem persists. (As do others.
See Item M33.)
Finally, it's worth mentioning that it can be convenient to declare pure virtual destructors in some classes.
Recall that pure virtual functions result in abstract classes ? classes that can't be instantiated (i.e., you can't
create objects of that type). Sometimes, however, you have a class that you'd like to be abstract, but you don't
happen to have any functions that are pure virtual. What to do? Well, because an abstract class is intended to be
used as a base class, and because a base class should have a virtual destructor, and because a pure virtual
function yields an abstract class, the solution is simple: declare a pure virtual destructor in the class you want to
be abstract.
Here's an example:
class AWOV {
public:
virtual ~AWOV() = 0;
// AWOV = "Abstract w/o
// Virtuals"
// declare pure virtual
// destructor
};
This class has a pure virtual function, so it's abstract, and it has a virtual destructor, so you can rest assured that
you won't have to worry about the destructor problem. There is one twist, however: you must provide a
definition for the pure virtual destructor:
AWOV::~AWOV() {}
// definition of pure
// virtual destructor
You need this definition, because the way virtual destructors work is that the most derived class's destructor is
called first, then the destructor of each base class is called. That means that compilers will generate a call to
~AWOV even though the class is abstract, so you have to be sure to provide a body for the function. If you don't,
the linker will complain about a missing symbol, and you'll have to go back and add one.
You can do anything you like in that function, but, as in the example above, it's not uncommon to have nothing to
do. If that is the case, you'll probably be tempted to avoid paying the overhead cost of a call to an empty function
by declaring your destructor inline. That's a perfectly sensible strategy, but there's a twist you should know
about.
Because your destructor is virtual, its address must be entered into the class's vtbl (see Item M24). But inline
functions aren't supposed to exist as freestanding functions (that's what inline means, right?), so special measures
must be taken to get addresses for them. Item 33 tells the full story, but the bottom line is this: if you declare a
virtual destructor inline, you're likely to avoid function call overhead when it's invoked, but your compiler will
still have to generate an out-of-line copy of the function somewhere, too.

Comments

Popular posts from this blog

CKA Simulator Kubernetes 1.22

  https://killer.sh Pre Setup Once you've gained access to your terminal it might be wise to spend ~1 minute to setup your environment. You could set these: alias k = kubectl                         # will already be pre-configured export do = "--dry-run=client -o yaml"     # k get pod x $do export now = "--force --grace-period 0"   # k delete pod x $now Vim To make vim use 2 spaces for a tab edit ~/.vimrc to contain: set tabstop=2 set expandtab set shiftwidth=2 More setup suggestions are in the tips section .     Question 1 | Contexts Task weight: 1%   You have access to multiple clusters from your main terminal through kubectl contexts. Write all those context names into /opt/course/1/contexts . Next write a command to display the current context into /opt/course/1/context_default_kubectl.sh , the command should use kubectl . Finally write a second command doing the same thing into ...

OWASP Top 10 Threats and Mitigations Exam - Single Select

Last updated 4 Aug 11 Course Title: OWASP Top 10 Threats and Mitigation Exam Questions - Single Select 1) Which of the following consequences is most likely to occur due to an injection attack? Spoofing Cross-site request forgery Denial of service   Correct Insecure direct object references 2) Your application is created using a language that does not support a clear distinction between code and data. Which vulnerability is most likely to occur in your application? Injection   Correct Insecure direct object references Failure to restrict URL access Insufficient transport layer protection 3) Which of the following scenarios is most likely to cause an injection attack? Unvalidated input is embedded in an instruction stream.   Correct Unvalidated input can be distinguished from valid instructions. A Web application does not validate a client’s access to a resource. A Web action performs an operation on behalf of the user without checkin...