SGISTL源码阅读四 对象的构造与析构

SGISTL源码阅读四 对象的构造与析构

前言

前面我们提到,SGISTL将空间配置和对象的构造分开操作了,前面的文章我们对空间配置已经做了描述,下面我们来看一下如何构造和析构对象。

深入源码

construc
//接受一个指针和一个初值
template <class T1, class T2>
inline void construct(T1* p, const T2& value) {
  new (p) T1(value);
}

construct函数就只有简单的一行,你可能会疑惑,这里使用的也是new,和传统C++创建对象时的new有什么区别呢?
其实这里的newplacement new,它重载了operator new,用于在一个已经分配好的内存中(堆/栈)构造一个新的对象。

destory
//接受一个指针
template <class T>
inline void destroy(T* pointer) {
	//调用dtor ~T
    pointer->~T();
}
//接受两个迭代器。设法找出元素的数值型别
//利用__type_traits<T>(这个后面会介绍到,也是一个重点)
template <class ForwardIterator>
inline void destroy(ForwardIterator first, ForwardIterator last) {
  __destroy(first, last, value_type(first));
}
//如果元素的数值型别有non-trivial_destructor()
template <class ForwardIterator>
inline void
__destroy_aux(ForwardIterator first, ForwardIterator last, __false_type) {
  for ( ; first < last; ++first)
    destroy(&*first);
}
//如果元素的数值型别有trivial_destructor()
template <class ForwardIterator>
inline void __destroy_aux(ForwardIterator, ForwardIterator, __true_type) {}

//判断元素的数值型别是否有trivial_destructor()
template <class ForwardIterator, class T>
inline void __destroy(ForwardIterator first, ForwardIterator last, T*) {
  typedef typename __type_traits<T>::has_trivial_destructor trivial_destructor;
  __destroy_aux(first, last, trivial_destructor());
}
//以下是 destroy()第二版本针对迭代器为char*和wchar*的特化版
inline void destroy(char*, char*) {}
inline void destroy(wchar_t*, wchar_t*) {}

可以看到destroy的版本大致为两种
1.接受一个指针
2.接受两个迭代器
可能现在有一些东西我们还不能看得很懂,后续会慢慢讲解到。

总结

本次我们了解到了constructdestory,它们根据不同的情况作了不同的相应措施,大大的提高了效率。

猜你喜欢

转载自blog.csdn.net/lyn_00/article/details/83959132