MSVC2019的vector标准库实现源码分析
好记性不如烂博客;stl源码剖析那本书不想看,没事(有事懒得做)看看微软的vector实现。
以vector<int> 为例
template <class _Ty, class _Alloc = allocator<_Ty>>
class vector { // varying size array of values
private:
template <class>
friend class _Vb_val;//????
friend _Tidy_guard<vector>;
using _Alty = _Rebind_alloc_t<_Alloc, _Ty>;//会区分是不是默认分配器_Default_allocator_traits或自定义allocator,是默认的话,就是本身allocator<int>,否则。。。模板嵌套太多了。。
using _Alty_traits = allocator_traits<_Alty>;
public:
static_assert(!_ENFORCE_MATCHING_ALLOCATORS || is_same_v<_Ty, typename _Alloc::value_type>,
_MISMATCHED_ALLOCATOR_MESSAGE("vector<T, Allocator>", "T"));
using value_type = _Ty;//int
using allocator_type = _Alloc;//
using pointer = typename _Alty_traits::pointer;
using const_pointer = typename _Alty_traits::const_pointer;
using reference = _Ty&;
using const_reference = const _Ty&;
using size_type = typename _Alty_traits::size_type;
using difference_type = typename _Alty_traits::difference_type;
private:
//template <class _Alloc> // tests if allocator has simple addressing
//_INLINE_VAR constexpr bool _Is_simple_alloc_v = is_same_v<typename allocator_traits<_Alloc>::size_type, size_t>&&
//is_same_v<typename allocator_traits<_Alloc>::difference_type, ptrdiff_t>&&
//is_same_v<typename allocator_traits<_Alloc>::pointer, typename _Alloc::value_type*>&&
//is_same_v<typename allocator_traits<_Alloc>::const_pointer, const typename _Alloc::value_type*>;
using _Scary_val = _Vector_val<conditional_t<_Is_simple_alloc_v<_Alty>, _Simple_types<_Ty>,
_Vec_iter_types<_Ty, size_type, difference_type, pointer, const_pointer, _Ty&, const _Ty&>>>;//是否是simple类型,选择不同的types,
只要不是自定义类型,应该都是选择第一个,其实第二个无非也是用自定义的类型。
public:
using iterator = _Vector_iterator<_Scary_val>;
using const_iterator = _Vector_const_iterator<_Scary_val>;
using reverse_iterator = _STD reverse_iterator<iterator>;
using const_reverse_iterator = _STD reverse_iterator<const_iterator>;
//两个构造函数同理,区分自定义分配器类型 #define _GET_PROXY_ALLOCATOR(_Alty, _Al) static_cast<_Rebind_alloc_t<_Alty, _Container_proxy>>(_Al) 这种写法第一次见,参数没有实际作用,构造一个新对象
_CONSTEXPR20_CONTAINER vector() noexcept(is_nothrow_default_constructible_v<_Alty>)
: _Mypair(_Zero_then_variadic_args_t{}) {
_Mypair._Myval2._Alloc_proxy(_GET_PROXY_ALLOCATOR(_Alty, _Getal()));//_GET_PROXY_ALLOCATOR(_Alty, _Getal()),构造一个allocator<_Container_proxy>
}
_CONSTEXPR20_CONTAINER explicit vector(const _Alloc& _Al) noexcept : _Mypair(_One_then_variadic_args_t{}, _Al) { _Mypair._Myval2._Alloc_proxy(_GET_PROXY_ALLOCATOR(_Alty, _Getal())); }
_Compressed_pair<_Alty, _Scary_val> _Mypair;//仅有的成员变量,实际继承第一个模板参数,负责分配数据内存,并持有一个_Scary_val的变量,负责管理数据
......
......
}


