Created
March 11, 2017 14:44
-
-
Save pebble8888/f7af6dabd4a522a79e8d40a6bafbadfa to your computer and use it in GitHub Desktop.
C++ allocator sample
This file contains hidden or 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 <cstdlib> | |
| template <class T> | |
| struct MyAllocator { | |
| using value_type = T; | |
| // default constractor | |
| // copy constractor | |
| // move constractor | |
| MyAllocator() | |
| { | |
| } | |
| template <class U> | |
| MyAllocator(const MyAllocator<U>&) | |
| { | |
| } | |
| T* allocate(std::size_t n) | |
| { | |
| return reinterpret_cast<T*>(std::malloc(sizeof(T) * n)); | |
| } | |
| void deallocate(T* p, std::size_t n) | |
| { | |
| static_cast<void>(n); | |
| std::free(p); | |
| } | |
| }; | |
| // compare operator | |
| template <class T, class U> | |
| bool operator==(const MyAllocator<T>&, const MyAllocator<U>&) | |
| { | |
| return true; | |
| } | |
| template <class T, class U> | |
| bool operator!=(const MyAllocator<T>&, const MyAllocator<U>&) | |
| { | |
| return false; | |
| } | |
| #include <vector> | |
| #include <list> | |
| int main() | |
| { | |
| std::vector<int, MyAllocator<int>> v = {1, 2, 3}; | |
| std::list<int, MyAllocator<int>> ls = {4, 5, 6}; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment