COMS W4995 C++ Deep Dive for C Programmers

Type Erasure

This chapter is still a draft, expect rough edges!

Motivation: Smart Pointer Deleters

In chapter 17, we demonstrated that both std::unique_ptr and std::shared_ptr can accept custom deleters. However, their type signatures are not the same:

template <typename T,
          typename Deleter = std::default_delete<T>>
class unique_ptr;

template <typename T>
class shared_ptr;

The key difference is that the deleter is part of unique_ptr’s type, but not shared_ptr’s type. We can’t move one unique_ptr into another unless their deleter types match, but we can assign one shared_ptr<int> to another even when they hold different deleters. This is demonstrated in the the program 20/smart-ptr-deleters below:

struct DelFunctor {
    void operator()(int* p) const {
        delete p;
    }
};

int main() {
    auto del_lambda = [](int* p) {
        delete p;
    };

    // unique_ptr: deleter is part of the type
    std::unique_ptr<int, DelFunctor> u1(new int(1));
    std::unique_ptr<int, decltype(del_lambda)> u2(new int(2), del_lambda);

    // error: u1 and u2 have different types!
    // u1 = std::move(u2);

    std::unique_ptr<int, DelFunctor> u3(new int(3));
    // OK: both are unique_ptr<int, DelFunctor>
    u1 = std::move(u3);

    // shared_ptr: deleter is not part of the type
    std::shared_ptr<int> s1(new int(1), DelFunctor{});
    std::shared_ptr<int> s2(new int(2), del_lambda);
    // OK: both are shared_ptr<int>
    s1 = s2;
}

The program is using smart pointers with custom deleters to manage a heap-allocated integer. The first custom deleter is DelFunctor, which is a simple struct that defines operator(). The second deleter is the lambda we assign to del_lambda. They both do the same thing (delete p) but the two deleters have different types.

Since u1 and u2 have different types, we cannot move u2 into u1. We can only move one unique_ptr into another if they have the same value and deleter functor type, as is the case for moving u3 into u1.

We can, however, copy assign s2 into s1 even though they were constructed with different deleters. Their types are both shared_ptr<int>. They were created with the following templated constructor:

template<typename T, typename Deleter> 
shared_ptr(T* ptr, Deleter d);

This constructor is templated not only on the pointer type, but also on the deleter type. Even though shared_ptr can be created with any deleter through this constructor, that deleter is not part of shared_ptr’s type. The deleter’s type has been hidden, or “erased”. This technique is known as type erasure, where a concrete type is hidden behind a single uniform interface, so unrelated types can be stored and used interchangeably.

In this chapter, we will study how to implement type erasure and explore C++ utilities that are built on top of them: std::shared_ptr, std::function, std::any, and std::variant.

std::shared_ptr

In this section, we will extend our SharedPtr<T> implementation from previous chapter to support a type-erased deleter. Before that, we introduce the C++ coding pattern that std::shared_ptr employs to erase its deleter: the concep-model idiom.

Concept-Model Idiom

We’re going to build class Deleter<T>, which is any functor that defines: void operator()(T*) and is used to delete the ptr. We’re then going to try to incorporate it into our SharedPtr. Here is the implementation of Deleter<T>, written in the concept-model style:

template <typename T>
class Deleter {
public:
    template <typename F>
    Deleter(F f) : impl{new Model<F>{std::move(f)}} {}
    void operator()(T* p) { (*impl)(p); }
private:
    struct Concept {
        virtual void operator()(T*) = 0;
        virtual ~Concept() = default;
    };
    template <typename F>
    struct Model : Concept {
        F f;
        Model(F f) : f{std::move(f)} {}
        void operator()(T* p) override { f(p); }
    };

    std::unique_ptr<Concept> impl;
};

There are three components to the concept-model idiom:

  1. Public “wrapper” class: Our Deleter<T> will be the public interface that can erase any deleter functor we construct it with. It holds the functor and exposes its operator().
  2. Private “concept” class: This is an abstract class that defines all functions that the erased type must implement. In our case, the erased functor must implement void operator()(T*)
  3. Private “model” class template: This class template inherits from the concept classs and implements all of its functions. It is templated so it can be instatiated with any functor F that implements the necessary operator(). The wrapper class will hold a pointer to an instance of this model through the non-templated concept base class.

TODO: Jae diagram

Deleter<T> is only templated on the value type that we’re going to delete a pointer to. However, it’s constructor is defined as a function template that can accept any functor F. The constructor will heap-allocate an instance of Model<F> and hold a unique_ptr to it through the Concept base class. Deleter can’t declare a member Concept impl; because Concept is an abstract class and we can’t instantiate abstract classes. Deleter also can’t hold Model<F> impl; because Deleter would then have to be templated as well. To prevent wasteful copies of the functor, we move it across the layers.

The following test program demonstrates the usage of Deleter<T>:

struct DelFunctor {
    void operator()(int* p) const {
        std::cout << "DelFunctor\n";
        delete p;
    }
};

int main() {
    auto del_lambda = [](int* p) {
        std::cout << "del_lambda\n";
        delete p;
    };

    // different functor types, same Deleter<int> type
    Deleter<int> d1{DelFunctor{}};
    Deleter<int> d2{del_lambda};

    // Deleters can delete int* pointers.
    d1(new int(1));
    d2(new int(2));

    d1 = std::move(d2);  // OK: Deleter<int> is movable
    d1(new int(3));      // now calls del_lambda

    // error: Deleter<int> is not copyable (its unique_ptr member is move-only)
    // Deleter<int> d3 = d1;
    // d1 = d3;
}

The program produces the following output:

$ ./shared-ptr-with-deleter 
DelFunctor
del_lambda
del_lambda

We create two Deleter objects, d1 and d2, out of the functor and lambda types, respectively. We then demonstrate that they can delete int* pointers. Despite holding different underlying functor types, we can move-assign from d2 into d1. The subsequent call to d1 invokes the lambda functor.

The following code snippet tries to copy construct d3 out of d1, but it doesn’t compile:

Deleter<int> d3 = d1;

The compilation error points out that Deleter’s copy operations are implicity deleted because of the unique_ptr member, which can’t be copied:

shared-ptr-with-deleter.cpp: error: call to implicitly-deleted copy constructor of 'Deleter<int>'
      |     Deleter<int> d3 = d1;
      |                  ^    ~~
shared-ptr-with-deleter.cpp: note: copy constructor of 'Deleter<int>' is implicitly deleted because field 'impl' has a deleted copy constructor
      |     std::unique_ptr<Concept> impl;

We need to perform a copy of the erased functor so we can copy Deleter, but Deleter doesn’t know the type of the erased functor! Deleter only has a pointer to the erased type via Concept, but we can’t copy Concept either since it’s an abstract class!

Deleter must instead delegate the copy operation to the Model<F> layer, which does know the type of the underlying functor (F). Here is the updated implementation of Model<F>:

template <typename F>
struct Model : Concept {
    F f;
    Model(F f) : f{std::move(f)} {}
    std::unique_ptr<Concept> clone() const override {
        return std::make_unique<Model<F>>(f);
    }
    void operator()(T* p) override { f(p); }
};

The clone() method makes a new copy of Model<F> and wraps it in a unique_ptr. Note that return type – we intentionally return unique_ptr<Concept> instead of unique_ptr<Model<F>> because we can’t leak the erased type up Deleter. This is known as the virtual constructor pattern. You can’t actually have a virtual constructor in C++, but we’ve effectively achieved that here. clone() creates a copy of the derived class without the caller knowing what the derived class even is.

clone() is a pure virtual function defined by Concept so that it can be implemented by Model<T> and called by Deleter. Here is the updated version of Concept:

struct Concept {
    virtual void operator()(T*) = 0;
    virtual std::unique_ptr<Concept> clone() const = 0;
    virtual ~Concept() = default;
};

Finally, Deleter can now define copy operations by invoking clone() on its pointer to the erased type:

template <typename T>
class Deleter {
public:
    template <typename F>
    Deleter(F f) : impl{new Model<F>{std::move(f)}} {}
    void operator()(T* p) { (*impl)(p); }

    Deleter(const Deleter& other) : impl{other.impl->clone()} {}
    Deleter& operator=(const Deleter& other) {
        impl = other.impl->clone();
        return *this;
    }
    Deleter(Deleter&&) = default;
    Deleter& operator=(Deleter&&) = default;
...
};

Deleter’s copy constructor move-constructs its unique_ptr from the return value of other.impl->clone(). The copy assignment operation move-assigns from other.impl->clone(), dropping the previously held pointer.

The addition of clone() highlights the difference between the public API that the Deleter wrapper exposes and the private API enforced by Concept. Deleter implements the public API using the virtual methods defined by Concept.

SharedPtr With Type-Erased Deleter

We’re now ready to extend our SharedPtr implementation to support a custom deleter. In this first approach, we simply add the Deleter as a member variable of SharedPtr:

template <typename T>
class SharedPtr {
    T*         ptr;    // the underlying pointer
    int*       count;  // the reference count
    Deleter<T> del;    // each SharedPtr holds its own copy of the deleter

    void detach() {
        if (--*count == 0) {
            delete count;
            del(ptr);
        }
    }
public:
    explicit SharedPtr(T* p) : SharedPtr(p, default_delete<T>{}) {}

    template <typename F>
    SharedPtr(T* p, F f) : ptr{p}, count{new int{1}}, del{std::move(f)} {}

    ~SharedPtr() { detach(); }

    SharedPtr(const SharedPtr& sp) : ptr{sp.ptr}, count{sp.count}, del{sp.del} {
        ++*count;
    }
    SharedPtr& operator=(const SharedPtr& sp) {
        if (this != &sp) {
            detach();
            ptr = sp.ptr;
            count = sp.count;
            del = sp.del;
            ++*count;
        }
        return *this;
    }

    T& operator*() const { return *ptr; }
    T* operator->() const { return ptr; }
    int get_count() const { return *count; }
};

SharedPtr now defines two constructors:

explicit SharedPtr(T* p) : SharedPtr(p, default_delete<T>{}) {}

template <typename F>
SharedPtr(T* p, F f) : ptr{p}, count{new int{1}}, del{std::move(f)} {}

The templated constructor accepts a pointer to manage and a deleter functor of type F. The original constructor delegates to the new templated constructor by providing std::default_delete as the deleter.

In this implementation, every SharedPtr attached to the same managed pointer has a copy of the same deleter functor. Whoever detaches last will invoke the deleter functor on the pointer:

void detach() {
    if (--*count == 0) {
        delete count;
        del(ptr);
    }
}

The code snippet below exercises the new deleter functionality:

SharedPtr<int> s1(new int(1), DelFunctor{});
SharedPtr<int> s2(new int(2), del_lambda);
s1 = s2;  // s1's old int is freed with DelFunctor
cout << "count: " << s1.get_count() << "\n";

It produces the following output:

DelFunctor
count: 2
del_lambda

s1 and s2 are constructed with DelFunctor and del_lambda, respectively, and manage their own pointers. When we do the assignment s1 = s2, s1 deletes its managed pointer with DelFunctor before attaching to s2’s managed pointer and copying its deleter.

Given that the deleter is a member of SharedPtr, we had to ensure Deleter is copiable so SharedPtr could still be copiable. This is why we implemented clone() in the previous section.

While this implementation is simple and works, there is a clear design flaw. It’s wasteful that SharedPtr holds the deleter functor directly, considering that all SharedPtrs attached to the same managed pointer hold a copy of the same deleter, too.

The real std::shared_ptr doesn’t put the deleter in SharedPtr. Recall from our discussion of shared_ptr in chapter 17 that the real implementation allocates a control block on the heap that stores the shared reference count and weak count, as well as other metadata. It turns out that the deleter also goes into the control block! This ensures only one copy of the functor is allocated.

A straightforward approach to adapt this into our SharedPtr would be to use the following struct:

struct ControlBlock {
    int count = 1;
    Deleter<T> del;
};

Our SharedPtr can allocate a ControlBlock and share the pointer to it. While this works, there is one downside. This requires SharedPtr to perform two heap allocations: one for the ControlBlock and one inside the implementation of Deleter. The real shared_ptr implementation performs only one allocation for the control block by embedding the concept-model idiom into the definition of the control block, instead of using a separate type for the deleter (e.g., std::function, which is what our Deleter approximates).

Here are the relevant changes to our SharedPtr:

template <typename T>
class SharedPtr {
    struct ControlBlock {
        int count = 1;
        virtual void destroy(T* p) = 0;
        virtual ~ControlBlock() = default;
    };
    template <typename F>
    struct Model : ControlBlock {
        F del;
        Model(F f) : del{std::move(f)} {}
        void destroy(T* p) override { del(p); }
    };

    T* ptr;
    ControlBlock* cb;

    void detach() {
        if (--cb->count == 0) {
            cb->destroy(ptr);
            delete cb;
        }
    }
public:
    explicit SharedPtr(T* p) : SharedPtr(p, default_delete<T>{}) {}

    template <typename F>
    SharedPtr(T* p, F f) : ptr{p}, cb{new Model<F>{std::move(f)}} {}
...
};

SharedPtr now holds two pointers: the stored pointer and a pointer to the control block. The SharedPtr constructor allocates the control block on the heap. The control block holds the shared reference count and the erased deleter functor. SharedPtr now implements the concept-model idiom:

The code presented captures the essence of the std::shared_ptr implementation. There are subtleties to the implementation that we didn’t have to worry about since we don’t support aliasing constructor or weak_ptr semantics, which we covered in chapter 17. To support aliasing, shared_ptr stores the managed pointer in the control block because shared_ptr’s pointer might not point to the whole object. If our SharedPtr supported aliasing, we’d need to store the managed pointer in control block to ensure we delete the right pointer. To support weak_ptr semantics, shared_ptr stores a count of attached weak_ptrs in the control block. The control block is only deleted once the shared_ptr and weak_ptr counts hit zero, but the managed pointer gets deleted once the former hits zero. This is so that weak_ptr always points to a valid control block and learn that the resource has expired because all the shared_ptrs were destroyed.

std::function

Our Deleter is pretty much the basis of std::function!

More coming soon