Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Understanding C++ Quirks and Oddities

C Utilities

Recall that C++ is a superset of C, and thus contains all of its functionality. There are a few obscure C features that have no replacement in C++, and which can occasionally be useful. This section examines two of these features: variable-length argument lists and preprocessor macros.

Variable-Length Argument Lists

Consider the C function printf() from <cstdio>. You can call it with any number of arguments:

#include <cstdio>

int main(int argc, char** argv)

{

printf(“int %d\n”, 5);

printf(“String %s and int %d\n”, “hello”, 5); printf(“Many ints: %d, %d, %d, %d, %d\n”, 1, 2, 3, 4, 5);

}

C++ provides the syntax and some utility macros for writing your own functions with a variable number of arguments. These functions usually look a lot like printf(). Although you shouldn’t need this feature very often, occasionally you run into situations in which it’s quite useful. For example, suppose you want to write a quick-and-dirty debug function that prints strings to stderr if a debug flag is set, but does nothing if the debug flag is not set. This function should be able to print strings with arbitrary numbers and types of arguments. A simple implementation looks like this:

#include <cstdio> #include <cstdarg>

bool debug = false;

void debugOut(char* str, ...)

{

va_list ap; if (debug) {

va_start(ap, str); vfprintf(stderr, str, ap); va_end(ap);

}

}

First, note that the prototype for debugOut() contains one typed and named parameter str, followed by ... (ellipses). They stand for any number and types of arguments. In order to access these arguments, you must use macros defined in <cstdarg>. You declare a variable of type va_list, and initialize it with a call to va_start. The second parameter to va_start() must be the rightmost named variable in the parameter list. All functions require at least one named parameter. The debugOut() function simply passes this list to vfprintf() (a standard function in <cstdio>). After this function completes, it calls va_end() to terminate the access of the variable argument list. You must always call va_end() after calling va_start() to ensure that the function ends with the stack in a consistent state.

345

Chapter 12

You can use the function in the following way:

int main(int argc, char** argv)

{

debug = true; debugOut(“int %d\n”, 5);

debugOut(“String %s and int %d\n”, “hello”, 5); debugOut(“Many ints: %d, %d, %d, %d, %d\n”, 1, 2, 3, 4, 5);

return (0);

}

Accessing the Arguments

If you want to access the actual arguments yourself, you can use va_arg() to do so. For example, here’s a function that takes any number of ints and prints them out:

#include <iostream> using namespace std;

void printInts(int num, ...)

{

int temp; va_list ap;

va_start(ap, num);

for (int i = 0; i < num; i++) { temp = va_arg(ap, int); cout << temp << “ “;

}

va_end(ap); cout << endl;

}

You can call printInts() like this:

printInts(5, 5, 4, 3, 2, 1);

Why You Shouldn’t Use Variable-Length Argument Lists

Accessing variable-length argument lists is not very safe. As you can see from the printInts() function, there are several risks:

You don’t know the number of parameters. In the case of printInts(), you must trust the caller to pass the right number of arguments in the first argument. In the case of debugOut(), you must trust the caller to pass the same number of arguments after the character array as there are formatting codes in the character array.

You don’t know the types of the arguments. va_arg() takes a type, which it uses to interpret the value it its current spot. However, you can tell va_arg() to interpret the value as any type. There is no way for it to verify the correct type.

346

Understanding C++ Quirks and Oddities

Avoid using variable-length argument lists. It is preferable to pass in an array or vector of variables.

Preprocessor Macros

You can use the C++ preprocessor to write macros, which are like little functions. Here is an example:

#define SQUARE(x) ((x) * (x)) // No semicolon after the macro definition!

int main(int argc, char** argv)

{

cout << SQUARE(4) << endl;

return (0);

}

Macros are a remnant from C that are quite similar to inline functions, except that they are not type checked, and the preprocessor dumbly replaces any calls to them with their expansions. The preprocessor does not apply true function-call semantics. This behavior can cause unexpected results. For example, consider what would happen if you called the SQUARE macro with 2 + 2 instead of 4, like this:

cout << SQUARE(2 + 2) << endl;

You expect SQUARE to calculate 16, which it does. However, what if you left off some parentheses on the macro definition, so that it looks like this?

#define SQUARE(x) (x * x)

Now, the call to SQUARE(2 + 2) generates 8, not 16! Remember that the macro is dumbly expanded without regard to function-call semantics. This means that any x in the macro body is replaced by

2 + 2, leading to this expansion:

cout << 2 + 2 * 2 + 2 << endl;

Following proper order of operations, this line performs the multiplication first, followed by the additions, generating 8 instead of 16!

Macros also cause problems for debugging because the code you write is not the code that the compiler sees, or that shows up in your debugger (because of the search and replace behavior of the preprocessor). For these reasons, you should avoid macros entirely in favor of inline functions. We show the details here only because quite a bit of C++ code out there employs macros. You need to understand them in order to read and maintain that code.

347

Chapter 12

Summar y

This chapter explained some of the aspects of C++ that generate the most confusion. By reading this chapter, you learned a plethora of syntax details about C++. Some of the information, such as the details of references, const, scope resolution, the specifics of the C++-style casts, and the techniques for header files, you should use often in your programs. Other information, such as the uses of static and extern, how to write variable-length argument lists, and how to write preprocessor macros, is important to understand, but not information that you should put into use in your programs on a day-to-day basis. In any case, now that you understand these details, you are poised to tackle the advanced C++ in the rest of the book.

348

Effective Memor y

Management

In many ways, programming in C++ is like driving without a road. Sure, you can go anywhere you want, but there are no lines or traffic lights to keep you from injuring yourself. C++, like the C language, has a hands-off approach towards its programmers. The language assumes that you know what you’re doing. It allows you to do things that are likely to cause problems because C++ is incredibly flexible and sacrifices safety in favor of performance.

Memory allocation and management is a particularly error-prone area of C++ programming. To write high-quality C++ programs, professional C++ programmers need to understand how memory works behind the scenes. This chapter explores the ins and outs of memory management. You will learn about the pitfalls of dynamic memory and some techniques for avoiding and eliminating them.

The chapter begins with an overview on the different ways to use and manage memory. Next, you will read about the often perplexing relationship between arrays and pointers. You will then learn about the creation and management of C-style strings. A low-level look at working with memory comes next. Finally, the last section of this chapter covers some specific problems that you may encounter with memory management and proposes a number of solutions.

Working with Dynamic Memor y

When learning to program, dynamic memory is often the first major stumbling block that novice programmers face. Memory is a low-level component of the computer that unfortunately rears its head even in a high-level programming language like C++. Many programmers only understand enough about dynamic memory to get by. They shy away from data structures that use dynamic memory, or get their programs to work by trial and error.