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

Overloading C++ Operators

In order to allow stream objects to be used in Boolean expressions, but prohibit their undesired promotion to int, the basic_ios class defines operator void* instead of operator bool.

A third alternative is to implement operator! and require clients of the class to use only negative comparisons, such as:

if (!smartCell) { cout << “NULL\n”;

}

As you can see, there is a design element to overloading operators. Your decisions about which operators to overload directly influence the ways in which clients can use your classes.

Overloading the Memor y Allocation and

Deallocation Operators

C++ gives you the ability to redefine the way memory allocation and deallocation work in your programs. You can provide this customization both on the global level and the class level. This capability is most useful when you are worried about performance and would like to provide more efficient memory management than is provided by default. For example, instead of going to the default C++ memory allocation each time you need memory, you could write a memory pool allocator that reuses fixed-size chunks of memory. This section explains the subtleties of the memory allocation and deallocation routines and shows you how to customize them. With these tools, you should be able to write a memory pool if the need ever arises.

Unless you know a lot about memory allocation strategies, attempts to overload the memory allocation routines are rarely worth the trouble. Don’t overload them just because it sounds like a neat idea. Only do so if you have a genuine performance or space requirement and the necessary knowledge.

How new and delete Really Work

One of the trickiest aspects of C++ is the details of new and delete. Consider this line of code:

SpreadsheetCell* cell = new SpreadsheetCell();

The new SpreadsheetCell() is called the new expression. It does two things. First, it allocates space for the SpreadsheetCell object by making a call to operator new. Second, it calls the constructor for the object. Only after the constructor has completed does it return the pointer to you.

delete functions similarly. Consider this line of code:

delete cell;

This line is called the delete expression. It first calls the destructor for cell, then calls operator delete to free the memory.

457

Chapter 16

When you use the keyword new to allocate memory, you are not directly calling operator new. When you use the keyword delete to free memory, you are not directly calling operator delete.

You can overload operator new and operator delete to control memory allocation and deallocation, but you cannot overload the new expression or the delete expression. Thus, you can customize the actual memory allocation and deallocation, but not the calls to the constructor and destructor.

The New Expression and operator new

There are six different forms of the new expression, each of which has a corresponding operator new. You’ve already seen the first four new expressions in Chapters 13 and 15: new, new[], nothrow new, and nothrow new[]. The operator news for each them are defined in the header file <new> and are reproduced here respectively:

void* operator new(size_t size) throw(bad_alloc); // For new void* operator new[](size_t size) throw(bad_alloc); // For new[]

void* operator new(size_t size, const nothrow_t&) throw(); // For nothrow new void* operator new[](size_t size, const nothrow_t&) throw(); // For nothrow new[]

The fifth and sixth forms of new are called placement new (including both single and array forms). They allow you to construct an object in preexisting memory like this:

void* ptr = allocateMemorySomehow();

SpreadsheetCell* cell = new (ptr) SpreadsheetCell();

This feature is a bit obscure, but it’s important to realize that it exists. It can come in handy if you want to implement memory pools such that you reuse memory without freeing it in between. The corresponding operator news look like this:

void* operator new(size_t size, void* p) throw();

void* operator new[](size_t size, void* p) throw();

The Delete Expression and operator delete

There are only two different forms of the delete expression that you can call: delete, and delete[]; there are no nothrow or placement forms. However, there are all six forms of operator delete. Why the asymmetry? The four nothrow and placement forms are used only if an exception is thrown from a constructor. In that case, the operator delete is called that matches the operator new that was used to allocate the memory prior to the constructor call. However, if you delete a pointer normally, delete will call either operator delete or operator delete[] (never the nothrow or placement forms). Practically, this doesn’t really matter: delete never throws an exception anyway, so the nothrow version of operator delete is superfluous, and placement delete should be a no-op. (The memory wasn’t allocated in placement operator new, so there’s nothing to free). Here are the prototypes for the operator delete forms:

void operator delete(void* ptr) throw(); void operator delete[](void* ptr) throw();

void operator delete(void* ptr, const nothrow_t&) throw();

458

Overloading C++ Operators

void operator delete[](void* ptr, const nothrow_t&) throw(); void operator delete(void* p, void*) throw();

void operator delete[](void* p, void*) throw();

Overloading operator new and operator delete

You can actually replace the global operator new and operator delete routines if you want. These functions are called for every new expression and delete expression in the program, unless there are more specific routines in individual classes. However, to quote Bjarne Stroustrup, “. . . replacing the global operator new() and operator delete() is not for the fainthearted.” (The C++ Programming Language, third edition). We don’t recommend it either!

If you fail to heed our advice and decide to replace the global operator new, keep in mind that you cannot put any code in the operator that makes a call to new: an infinite loop would result. For example, you cannot write a message to console with cout.

A more useful technique is to overload operator new and operator delete for specific classes. These overloaded operators will be called only when you allocate and deallocate objects of that particular class. Here is an example of a class that overloads the four nonplacement forms of operator new and operator delete:

#include <new> using namespace std;

class MemoryDemo

{

public: MemoryDemo() {} ~MemoryDemo() {}

void* operator new(size_t size) throw(bad_alloc); void operator delete(void* ptr) throw();

void* operator new[](size_t size) throw(bad_alloc); void operator delete[](void* ptr) throw();

void* operator new(size_t size, const nothrow_t&) throw(); void operator delete(void* ptr, const nothrow_t&) throw();

void* operator new[](size_t size, const nothrow_t&) throw(); void operator delete[](void* ptr, const nothrow_t&) throw();

};

Here are simple implementations of these operators that pass the argument through to calls to the global versions of the operators. Note that nothrow is actually a variable of type nothrow_t.

#include “MemoryDemo.h” #include <iostream> using namespace std;

459

Chapter 16

void* MemoryDemo::operator new(size_t size) throw(bad_alloc)

{

cout << “operator new\n”; return (::operator new(size));

}

void MemoryDemo::operator delete(void* ptr) throw()

{

cout << “operator delete\n”; ::operator delete(ptr);

}

void* MemoryDemo::operator new[](size_t size) throw(bad_alloc)

{

cout << “operator new[]\n”; return (::operator new[](size));

}

void MemoryDemo::operator delete[](void* ptr) throw()

{

cout << “operator delete[]\n”; ::operator delete[](ptr);

}

void* MemoryDemo::operator new(size_t size, const nothrow_t&) throw()

{

cout << “operator new nothrow\n”; return (::operator new(size, nothrow));

}

void MemoryDemo::operator delete(void* ptr, const nothrow_t&) throw()

{

cout << “operator delete nothrow\n”; ::operator delete[](ptr, nothrow);

}

void* MemoryDemo::operator new[](size_t size, const nothrow_t&) throw()

{

cout << “operator new[] nothrow\n”; return (::operator new[](size, nothrow));

}

void MemoryDemo::operator delete[](void* ptr, const nothrow_t&) throw()

{

cout << “operator delete[] nothrow\n”; ::operator delete[](ptr, nothrow);

}

Here is some code that allocates and frees objects of this class in several ways:

#include “MemoryDemo.h”

int main(int argc, char** argv)

{

MemoryDemo* mem = new MemoryDemo();

460