Created
January 20, 2019 11:31
-
-
Save kaoskorobase/38e15df544dd9b9866dcc2e28191f77c to your computer and use it in GitHub Desktop.
Faust DSP factory table using custom allocator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <list> | |
#include <map> | |
class memory_manager { | |
public: | |
void* allocate(size_t n) { return new char[n]; } | |
void destroy(void* ptr) { delete[] static_cast<char*>(ptr); } | |
}; | |
template <class T> | |
class custom_allocator { | |
memory_manager* m_manager; | |
public: | |
typedef T value_type; | |
template <class U> | |
struct rebind { | |
typedef custom_allocator<U> other; | |
}; | |
custom_allocator(memory_manager* manager) : m_manager(manager) {} | |
custom_allocator(const custom_allocator<T>& other) : m_manager(other.m_manager) {} | |
template <class U> | |
custom_allocator(const custom_allocator<U>& other) : m_manager(other.manager()) | |
{ | |
} | |
memory_manager* manager() const { return m_manager; } | |
T* allocate(std::size_t n) | |
{ | |
void* ptr = m_manager->allocate(n * sizeof(T)); | |
std::cout << "allocate " << ptr << " (" << n * sizeof(T) << ")" << std::endl; | |
return static_cast<T*>(ptr); | |
} | |
void deallocate(T* ptr, std::size_t n) | |
{ | |
std::cout << "deallocate " << ptr << " (" << n * sizeof(T) << ")" << std::endl; | |
m_manager->destroy(ptr); | |
} | |
}; | |
template <class T, class U> | |
constexpr bool operator==(const custom_allocator<T>& a, const custom_allocator<U>& b) noexcept | |
{ | |
return a.manager() == b.manager(); | |
} | |
template <class T, class U> | |
constexpr bool operator!=(const custom_allocator<T>& a, const custom_allocator<U>& b) noexcept | |
{ | |
return !(a == b); | |
} | |
struct dsp { | |
}; | |
typedef std::list<dsp*, custom_allocator<dsp*>> dsp_list; | |
typedef std::map<int, dsp_list, std::less<int>, custom_allocator<std::pair<const int, dsp_list>>> factory_map; | |
int main() | |
{ | |
memory_manager* m = new memory_manager(); | |
factory_map fm((factory_map::allocator_type(m))); | |
fm.emplace(0, dsp_list(dsp_list::allocator_type(m))); | |
fm.at(0).push_back(new dsp()); | |
// This doesn't compile: | |
// fm[0] = dsp_list(dsp_list::allocator_type(m)); | |
// fm[0].push_back(new dsp()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uncommenting line 73 fails with: