【发布时间】:2014-01-31 15:19:27
【问题描述】:
我像这样创建了自己的分配器:
template<typename T>
class BasicAllocator
{
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
BasicAllocator() throw() {};
BasicAllocator (const BasicAllocator& other) throw() {};
template<typename U>
BasicAllocator (const BasicAllocator<U>& other) throw() {};
template<typename U>
BasicAllocator& operator = (const BasicAllocator<U>& other) {return *this;}
BasicAllocator<T>& operator = (const BasicAllocator& other) {return *this;}
~BasicAllocator() {}
pointer address (reference value) const {return &value;}
const_pointer address (const_reference value) const {return &value;}
pointer allocate (size_type n, const void* hint = 0) {return static_cast<pointer> (::operator new (n * sizeof (value_type) ) );}
void deallocate (void* ptr, size_type n) {::operator delete (static_cast<T*> (ptr) );}
template<typename U, typename... Args>
void construct (U* ptr, Args&& ... args) {::new (static_cast<void*> (ptr) ) U (std::forward<Args> (args)...);}
void construct (pointer ptr, const T& val) {new (static_cast<T*> (ptr) ) T (val);}
template<typename U>
void destroy (U* ptr) {ptr->~U();}
void destroy (pointer ptr) {ptr->~T();}
size_type max_size() const {return std::numeric_limits<std::size_t>::max() / sizeof (T);} /**return std::size_t(-1);**/
template<typename U>
struct rebind
{
typedef BasicAllocator<U> other;
};
};
但我想知道为什么我永远不应该从std::allocator 继承。是因为它没有虚拟析构函数吗?我看过很多帖子说应该创建自己的而不是继承。我明白为什么我们不应该继承 std::string 和 std::vector 但继承 std::allocator 有什么问题?
我可以继承上面的类吗?还是我需要一个虚拟析构函数来做到这一点?
为什么?
【问题讨论】:
-
new (static_cast<T*> (ptr) )看起来像是一个错字(该函数已经使用了pointer == T*) -
在
std::vector或std::string之后继承完全没问题。您可以使用私有或受保护的继承安全地执行此操作,然后使用using关键字公开其接口的所需部分。
标签: c++ inheritance c++11