📖
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 10: Smart Pointers

Custom Deleters

Smart pointers ensure the automatic release of resources on the heap. In the previous example, our custom SmartPtr release the resources by calling delete on the pointer. However, delete is not always the correct way to release resources. For example, array objects need to be destroyed with delete[], and files need to be closed with fclose(). Therefore, under some circumstances we need to customize the deleter.

unique_ptr 和 shared_ptr both support custom deleters. Inside their destructors a function object of the deleter is called. The default deleter simply uses delete:

template <typename T>
class Deleter {
public:
    void operator() (T *ptr) {
        delete ptr;
    }
};

Now if we use a unique_ptr to point to an array, we can defined our own deleter which uses delete[] to free the memory. Then we need to use MyDeleter as a template parameter.

template <typename T>
class MyDeleter {
public:
    void operator() (T *ptr) const {
        delete[] ptr;
    }
};
​
int main() {
    unique_ptr<int, MyDeleter<int>> p = new int[100];
    return 0;
}

Similarly, we can also customize a deleter to release a file resource with fclose():

template <typename T>
class MyDeleter {
public:
    void operator() (T *ptr) const {
        fclose(ptr);
    }
};
​
int main() {
    unique_ptr<FILE, MyDeleter<FILE>> p = fopen("data.txt", "w");
    return 0;
}

In modern C++, a more convenient way to use custom deleters is to use the lambda expressions. The above examples can also be written as follows, without additional definitions of function objects.

#include <functional>
int main() {
    unique_ptr<int, function<void (int *)>> p1(new int[100], 
        [](int *p) -> void {
            delete[] p;
        }
    );
    unique_ptr<FILE, function<void (FILE *)>> p2(fopen("data.txt", "w"), 
        [](FILE *p) -> void {
            fclose(p);
        }
    );
}
PreviousSmart Pointers with Reference CountingNextMore about Binders

Last updated 4 years ago

Was this helpful?