C++ Primer, Part IV : Advanced Topics

C++ Primer, Fifth Edition

Stanley B. Lippman
José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 strings
    
    a 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 expression
  • 
    delete sp;        // destroy *sp and free the memory to which sp points
    delete [] arr;    // destroy the elements in the array and free the memory
    
    the 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); 
}

19.2 Run-Time Type Identification

19.3 Enumerations

19.4 Pointer to Class Member

19.5 Nested Classes

19.6 union: A Space-Saving Class

19.7 Local Classes

19.8 Inherently Nonportable Features





留言

熱門文章