Last active
August 29, 2015 14:10
-
-
Save zhangyuchi/ea7e06cd4b57916d82b6 to your computer and use it in GitHub Desktop.
allocator of shared
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 <memory> | |
//full version | |
template<typename T> | |
struct Allocator | |
{ | |
typedef std::size_t size_type; | |
typedef std::ptrdiff_t difference_type; | |
typedef T* pointer; | |
typedef const T* const_pointer; | |
typedef T& reference; | |
typedef const T& const_reference; | |
typedef T value_type; | |
template<typename U> | |
struct rebind {typedef Allocator<U> other;}; | |
Allocator() throw() {}; | |
Allocator(const Allocator& other) throw() {}; | |
template<typename U> | |
Allocator(const Allocator<U>& other) throw() {}; | |
template<typename U> | |
Allocator& operator = (const Allocator<U>& other) { return *this; } | |
Allocator<T>& operator = (const Allocator& other) { return *this; } | |
~Allocator() {} | |
pointer allocate(size_type n, const void* hint = 0) | |
{ | |
return static_cast<T*>(::operator new(n * sizeof(T))); | |
} | |
void deallocate(T* ptr, size_type n) | |
{ | |
::operator delete(ptr); | |
} | |
}; | |
template <typename T, typename U> | |
inline bool operator == (const Allocator<T>&, const Allocator<U>&) | |
{ | |
return true; | |
} | |
template <typename T, typename U> | |
inline bool operator != (const Allocator<T>& a, const Allocator<U>& b) | |
{ | |
return !(a == b); | |
} | |
//least version | |
template<typename T> | |
struct Allocator | |
{ | |
typedef T value_type; | |
Allocator() noexcept {}; | |
template<typename U> | |
Allocator(const Allocator<U>& other) throw() {}; | |
T* allocate(std::size_t n, const void* hint = 0) | |
{ | |
return static_cast<T*>(::operator new(n * sizeof(T))); | |
} | |
void deallocate(T* ptr, size_type n) | |
{ | |
::operator delete(ptr); | |
} | |
}; | |
template <typename T, typename U> | |
inline bool operator == (const Allocator<T>&, const Allocator<U>&) | |
{ | |
return true; | |
} | |
template <typename T, typename U> | |
inline bool operator != (const Allocator<T>& a, const Allocator<U>& b) | |
{ | |
return !(a == b); | |
} | |
int main() | |
{ | |
std::allocate_shared<int, Allocator<int>>(Allocator<int>(), 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment