最后我们使用一个hash_destruct的函数来获取出这个类型是否有析构函数。
template
inline auto has_destruct(const T&)->decltype(static_cast<__type_traits
{
return static_cast
}
template
inline auto has_destruct(T*)->decltype(static_cast<__type_traits
{
static_assert(false, "Please use const T& not T*");
return static_cast
}
template
inline auto has_destruct(const T*)->decltype(static_cast<__type_traits
{
static_assert(false, "Please use const T& not const T*");
return static_cast
}不得不提的是C++0x的确很强大,可以通过形参来确定返回值的类型,这样我们就可以萃取出这个类型的has_destruct域是__true_type或是__false_type了。
最后来看看construct和destruct的代码,在STL中对象的内存分配和构造是被分开的,对于基础对象int,char等,在析构时我们无需调用其析构函数。
下面来看construct和destruct的实现
template
inline void construct(T1* p, const T2& value)
{
new (p) T1(value);
}
template
inline void destruct(T* p, __true_type*)
{
p->~T();
}
template
inline void destruct(T*, __false_type*)
{
}
template
inline void destruct(ForwardIterator first, ForwardIterator last)
{
while(first != last)
{
destruct(first, has_destruct(*first));
++first;
}
}
lwch