📖
Go C++
  • Introduction
  • Chapter 1: What You Must Know First
    • Virtual Address Space of Process: Memory Partition and Layout
    • Function Call: Stack Frame
    • Program Compiling and Linking
  • Chapter 2: C++ Basics Improvement
    • Default Parameters
    • Inline Function
    • Function Overloading
    • new and delete
    • const and Pointers
    • References in Detail
  • Chapter 3: Object-Oriented Principles
  • Class and Object
  • Constructor and Destructor
  • Shallow Copy and Deep Copy
  • Initializer List
  • Various Member Functions
  • Pointer to Class Members
  • Chapter 4: Template Programming
  • Function Templates
  • Class Templates
  • Memory Allocators
  • Chapter 5: Operator Overloading
    • Operator Overloading
    • Introduction to Iterators
    • Issues of Iterator Invalidation
    • More about new and delete
    • Overloading of new and delete: Object Pool
  • Chapter 6: Inheritance and Polymorphism
    • Look inside Inheritance
    • More about Inheritance
    • Virtual Functions, Static Binding and Dynamic Binding
    • More about Virtual Functions
    • Understanding Polymorphism
    • Abstract Classes
    • Frequently Asked Interview Questions: Polymorphism
  • Chapter 7: Multiple Inheritance
    • Virtual Inheritance and Virtual Base Classes
    • Diamond Problem
    • Four Kinds of Type Conversions
  • Chapter 8: Standard Template Library
    • Sequence Containers
    • Container Adaptors
    • Associative Containers
    • More about Iterators
    • Function Objects
    • Generic Algorithms, Binders and Lambda Expressions
  • Chapter 9: Object Optimization
    • Behind the Object
    • Optimizing Objects in Functions
    • Member Functions with Rvalue References
    • Move Semantics and Perfect Forwarding
  • Chapter 10: Smart Pointers
    • Smart Pointers
    • Smart Pointers without Reference Counting
    • Smart Pointers with Reference Counting
    • Custom Deleters
  • Chapter 11: Function Objects and Binders
    • More about Binders
    • Introduction to std::function
    • Template Specialization and Argument Deduction
    • More about std::function
    • std::bind(): A Simple Thread Pool
    • More about Lambda Expressions
  • Chapter 12: Multithreading
    • Important Features in C++11
    • Multithreaded Programming with std::thread
    • Mutual Exclusion
    • Producer-Consumer Problem
    • Atomic Operations
    • Thread Visibility and volatile
  • Chapter 13: Design Patterns
    • Singleton Pattern
    • Factory Pattern
    • Proxy Pattern
    • Decorator Pattern
    • Adapter Pattern
    • Observer Pattern
Powered by GitBook
On this page

Was this helpful?

  1. Chapter 5: Operator Overloading

More about new and delete

new and delete are a couple of keywords in C++ for memory arrangement. Meanwhile, they are operators that can be overloaded as well. When new is used, the compiler will first calls function operator new() to allocate memory on heap, and then calls the corresponding constructor of the object. When delete is used, the compiler first calls the destructor, and then calls function operator delete() to deallocate the memory. Those are same for new[] and delete[], which is used for array elements.

The underlying implementations of operators new and delete are standard C functions malloc() and free(), which shows as follow. The former takes size of the object as parameter, and the latter takes the pointer of the object to be deleted as parameter.

void *operator new(size_t size) {
    void *p = malloc(size);
    if (p == nullptr)
        throw bad_alloc();
    return p;
}
​
void operator delete(void *p) {
    free(p);
}

Knowing this, we can overload them using our own-defined memory management functions. With overloading, we may track the allocated memory, for more precise and detailed memory management. It is widely used in a memory pool, or in checking memory leaks.

We already know that delete is used to free a single object, and delete[] is used to free an array object. But can these two be mixed used? Well, it depends.

In the following example, it is okay to use either of them. int is a built-in type instead of an object, so there's no constructor to be called. In this case, delete and delete[] are the same since their underlying implementations are the same.

int main() {
    int *p = new int;
    delete[] p;
    int *q = new int[10];
    delete q;
    return 0;
}

However, in the next example, incorrect use of these two will make the program crash:

class Test {
public:
    Test() {...}
    ~Test() {...}
private:
    int a;    
};
​
int main() {
    Test *t1 = new Test();
    delete[] t1;    // ERROR
    Test *t2 = new Test[5];
    delete t2;  // ERROR
    return 0;
}

It is because that objects need to be destroyed before deallocation. When new[] is used to create array objects, not only the memory space for these objects is allocated, an extra 4-byte space for recording the counts of objects is allocated as well. When delete[] is used, it first reads the counts n from it, then divides the memory space into n portions. In this way, the destructor of each array object can be called correctly. Unlike delete[], delete simply treats the whole memory space as a single object and frees it.

Therefore, if delete[] is used for a single object, it cannot find the count information. On the other hand, if delete is used for an array object, the freed memory has a 4-byte offset, and the destructors are not called properly as well.

PreviousIssues of Iterator InvalidationNextOverloading of new and delete: Object Pool

Last updated 5 years ago

Was this helpful?