📖
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 2: C++ Basics Improvement

new and delete

There are two ways to create memory on heap. One original approach in C style is to use the library functions malloc and free:

int main() {
    int *p = (int*)malloc(sizeof(int));
    if (p == nullptr) {
        return -1;
    }
    *p = 20;
    free(p);
    return 0;
}

Notice that malloc returns a type of void *, so we always need to cast it into the correct pointer type. What's more, we need to pass the size of allocated memory as the function argument. If the allocation fails, the function will return a NULL pointer, so we also need to check the validity of our pointer after the function call.

In C++, the memory allocation on heap can be done in a cleverer way: using operator new and delete.

int *p = new int(20);
delete p;

When using new, we no longer need to calculate the memory size nor cast the pointer type, thus things get much easier. Notice that new can also initialize the memory bucket after allocating it, just like the brackets we use in the code above. If the memory allocation fails, a bad_alloc exception is raised, we can then handle it with a try-catch structure.

When it's up to arrays, we can also allocate memory for it in a easy way. For new, we need to use square brackets, just like the way we declare an array on the stack. And for delete, we also need to add a pair of square brackets after it. delete[] will then loop through the array and operate delete to every element in the array.

Besides the conventional way to use new, there is also several other ways to use new. We can tell the program not to throw an exception if the allocation fails by stating (nothrow) after new.

int *p2 = new (nothrow) int;    // No exception

We can also assign constant memory on the heap with const keyword. In this way, the return pointer should be modified with const as well.

const int *p3 = new const int(40);  // Constant memory

Now all the memory address on the heap is allocated by the system. What if we want to allocate the memory on a specific location? We need to state the address of the destination after new, with brackets.

int data = 0;
int *p4 = new (&data) int(50);  // Memory allocated on &data
cout << data << endl;   // 50
PreviousFunction OverloadingNextconst and Pointers

Last updated 4 years ago

Was this helpful?