mercredi 21 février 2018

allocate_shared with malloc

I am trying to write a program on C++ but without using libstdc++. My program uses some header-only templates, and also it uses allocate_shared, to which I supply the custom allocator to avoid operators new and delete.

My problem is that I can only get rid of operator new. Operator delete is still referenced in the resulting object file.

#include <cstdlib>
#include <memory>

template <class T>
struct Mallocator {
  typedef T value_type;
  Mallocator() = default;
  template <class U> constexpr Mallocator(const Mallocator<U>&) noexcept {}
  T* allocate(std::size_t n) {
    return (T*)std::malloc(n*sizeof(T));
  }
  void deallocate(T* p, std::size_t) noexcept { std::free(p); }
};
template <class T, class U>
bool operator==(const Mallocator<T>&, const Mallocator<U>&) { return true; }
template <class T, class U>
bool operator!=(const Mallocator<T>&, const Mallocator<U>&) { return false; }

struct A {
    std::shared_ptr<int> a;
    A(const std::shared_ptr<int> b) : a(b) {}
};

int main()
{
    A a(std::allocate_shared<int>(Mallocator<int>(), 5));
    return 0;
}

Lets compile:

$ c++ -c malloca.cpp

And see what's there:

$ nm -u malloca.o | c++filt | grep new
$ nm -u malloca.o | c++filt | grep delete
U operator delete(void*, unsigned long)

Operator delete is still there, despite the custom allocator being provided. How can I get rid of it?

Aucun commentaire:

Enregistrer un commentaire