C++ Primer, Part IV : Advanced Topics
C++ Primer, Fifth Edition
Stanley B. LippmanJosée Lajoie
Barbara E. Moo
Chapter 17. Specialized Library Facilities
17.1 The tuple Type
17.2 The bitset Type
17.3 Regular Expressions
17.4 Random Numbers
17.5 The IO Library Revisited
Chapter 18. Tools for Large Programs
18.1 Exception Handling
18.2 Namespaces
18.3 Multiple and Virtual Inheritance
Chapter 19. Specialized Tools and Techniques
C++ is intended for use in a wide variety of applications.Many programmers will never (or only rarely) need to use the less-commonly features presented in this chapter.
19.1 Controlling Memory Allocation
19.1.1. Overloading new and delete
Take over the details of how memory is allocated- new expression
string *sp = new string("a value"); // allocate and initialize a string string *arr = new string[10]; // allocate ten default initialized stringsa library function named operator new (or operator new[]) allocates raw, untyped memory large enough to hold an object (or an array of objects) of the specified type. Then, the compiler runs the appropriate constructor to construct the object(s) from the specified initializers.
delete sp; // destroy *sp and free the memory to which sp points delete [] arr; // destroy the elements in the array and free the memorythe appropriate destructor is run on the object then the compiler frees the memory by calling a library function named operator delete or operator delete[ If you define your own global operator new and operator delete, those functions must allocate and deallocate memory somehow
A simple way to write operator new and operator delete is as follows:
void *operator new(size_t size) { if (void *mem = malloc(size)) return mem; else throw bad_alloc(); } void operator delete(void *mem) noexcept { free(mem); }
留言