目录
[2.3.1. 避免递归的模板依赖](#2.3.1. 避免递归的模板依赖)
[2.3.2. 内存布局一致性](#2.3.2. 内存布局一致性)
[2.3.3. 类型安全的替代方案](#2.3.3. 类型安全的替代方案)
[2.3.4. 与 C 风格链表的兼容性](#2.3.4. 与 C 风格链表的兼容性)
[2.3.5. 对比直接使用 __list_node * 的缺点](#2.3.5. 对比直接使用 __list_node * 的缺点)
[2.3.6. STL 的实际实现示例](#2.3.6. STL 的实际实现示例)
[总结:使用 void* 的原因](#总结:使用 void* 的原因)

1.std::list实现的所有代码
这是std::list函数的基本实现,一共有617行,如果不想看的话可以去到2,我会解释一部分:
cpp
/*
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Hewlett-Packard Company makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*
* Copyright (c) 1996,1997
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*/
/* NOTE: This is an internal header file, included by other STL headers.
* You should not attempt to use it directly.
*/
#ifndef __SGI_STL_INTERNAL_LIST_H
#define __SGI_STL_INTERNAL_LIST_H
__STL_BEGIN_NAMESPACE
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma set woff 1174
#endif
template <class T>
struct __list_node {
typedef void* void_pointer;
void_pointer next;
void_pointer prev;
T data;
};
template<class T, class Ref, class Ptr>
struct __list_iterator {
typedef __list_iterator<T, T&, T*> iterator;
typedef __list_iterator<T, const T&, const T*> const_iterator;
typedef __list_iterator<T, Ref, Ptr> self;
typedef bidirectional_iterator_tag iterator_category;
typedef T value_type;
typedef Ptr pointer;
typedef Ref reference;
typedef __list_node<T>* link_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
link_type node;
__list_iterator(link_type x) : node(x) {}
__list_iterator() {}
__list_iterator(const iterator& x) : node(x.node) {}
bool operator==(const self& x) const { return node == x.node; }
bool operator!=(const self& x) const { return node != x.node; }
reference operator*() const { return (*node).data; }
#ifndef __SGI_STL_NO_ARROW_OPERATOR
pointer operator->() const { return &(operator*()); }
#endif /* __SGI_STL_NO_ARROW_OPERATOR */
self& operator++() {
node = (link_type)((*node).next);
return *this;
}
self operator++(int) {
self tmp = *this;
++*this;
return tmp;
}
self& operator--() {
node = (link_type)((*node).prev);
return *this;
}
self operator--(int) {
self tmp = *this;
--*this;
return tmp;
}
};
#ifndef __STL_CLASS_PARTIAL_SPECIALIZATION
template <class T, class Ref, class Ptr>
inline bidirectional_iterator_tag
iterator_category(const __list_iterator<T, Ref, Ptr>&) {
return bidirectional_iterator_tag();
}
template <class T, class Ref, class Ptr>
inline T*
value_type(const __list_iterator<T, Ref, Ptr>&) {
return 0;
}
template <class T, class Ref, class Ptr>
inline ptrdiff_t*
distance_type(const __list_iterator<T, Ref, Ptr>&) {
return 0;
}
#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */
template <class T, class Alloc = alloc>
class list {
protected:
typedef void* void_pointer;
typedef __list_node<T> list_node;
typedef simple_alloc<list_node, Alloc> list_node_allocator;
public:
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef list_node* link_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
public:
typedef __list_iterator<T, T&, T*> iterator;
typedef __list_iterator<T, const T&, const T*> const_iterator;
#ifdef __STL_CLASS_PARTIAL_SPECIALIZATION
typedef reverse_iterator<const_iterator> const_reverse_iterator;
typedef reverse_iterator<iterator> reverse_iterator;
#else /* __STL_CLASS_PARTIAL_SPECIALIZATION */
typedef reverse_bidirectional_iterator<const_iterator, value_type,
const_reference, difference_type>
const_reverse_iterator;
typedef reverse_bidirectional_iterator<iterator, value_type, reference,
difference_type>
reverse_iterator;
#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */
protected:
link_type get_node() { return list_node_allocator::allocate(); }
void put_node(link_type p) { list_node_allocator::deallocate(p); }
link_type create_node(const T& x) {
link_type p = get_node();
__STL_TRY {
construct(&p->data, x);
}
__STL_UNWIND(put_node(p));
return p;
}
void destroy_node(link_type p) {
destroy(&p->data);
put_node(p);
}
protected:
void empty_initialize() {
node = get_node();
node->next = node;
node->prev = node;
}
void fill_initialize(size_type n, const T& value) {
empty_initialize();
__STL_TRY {
insert(begin(), n, value);
}
__STL_UNWIND(clear(); put_node(node));
}
#ifdef __STL_MEMBER_TEMPLATES
template <class InputIterator>
void range_initialize(InputIterator first, InputIterator last) {
empty_initialize();
__STL_TRY {
insert(begin(), first, last);
}
__STL_UNWIND(clear(); put_node(node));
}
#else /* __STL_MEMBER_TEMPLATES */
void range_initialize(const T* first, const T* last) {
empty_initialize();
__STL_TRY {
insert(begin(), first, last);
}
__STL_UNWIND(clear(); put_node(node));
}
void range_initialize(const_iterator first, const_iterator last) {
empty_initialize();
__STL_TRY {
insert(begin(), first, last);
}
__STL_UNWIND(clear(); put_node(node));
}
#endif /* __STL_MEMBER_TEMPLATES */
protected:
link_type node;
public:
list() { empty_initialize(); }
iterator begin() { return (link_type)((*node).next); }
const_iterator begin() const { return (link_type)((*node).next); }
iterator end() { return node; }
const_iterator end() const { return node; }
reverse_iterator rbegin() { return reverse_iterator(end()); }
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
bool empty() const { return node->next == node; }
size_type size() const {
size_type result = 0;
distance(begin(), end(), result);
return result;
}
size_type max_size() const { return size_type(-1); }
reference front() { return *begin(); }
const_reference front() const { return *begin(); }
reference back() { return *(--end()); }
const_reference back() const { return *(--end()); }
void swap(list<T, Alloc>& x) { __STD::swap(node, x.node); }
iterator insert(iterator position, const T& x) {
link_type tmp = create_node(x);
tmp->next = position.node;
tmp->prev = position.node->prev;
(link_type(position.node->prev))->next = tmp;
position.node->prev = tmp;
return tmp;
}
iterator insert(iterator position) { return insert(position, T()); }
#ifdef __STL_MEMBER_TEMPLATES
template <class InputIterator>
void insert(iterator position, InputIterator first, InputIterator last);
#else /* __STL_MEMBER_TEMPLATES */
void insert(iterator position, const T* first, const T* last);
void insert(iterator position,
const_iterator first, const_iterator last);
#endif /* __STL_MEMBER_TEMPLATES */
void insert(iterator pos, size_type n, const T& x);
void insert(iterator pos, int n, const T& x) {
insert(pos, (size_type)n, x);
}
void insert(iterator pos, long n, const T& x) {
insert(pos, (size_type)n, x);
}
void push_front(const T& x) { insert(begin(), x); }
void push_back(const T& x) { insert(end(), x); }
iterator erase(iterator position) {
link_type next_node = link_type(position.node->next);
link_type prev_node = link_type(position.node->prev);
prev_node->next = next_node;
next_node->prev = prev_node;
destroy_node(position.node);
return iterator(next_node);
}
iterator erase(iterator first, iterator last);
void resize(size_type new_size, const T& x);
void resize(size_type new_size) { resize(new_size, T()); }
void clear();
void pop_front() { erase(begin()); }
void pop_back() {
iterator tmp = end();
erase(--tmp);
}
list(size_type n, const T& value) { fill_initialize(n, value); }
list(int n, const T& value) { fill_initialize(n, value); }
list(long n, const T& value) { fill_initialize(n, value); }
explicit list(size_type n) { fill_initialize(n, T()); }
#ifdef __STL_MEMBER_TEMPLATES
template <class InputIterator>
list(InputIterator first, InputIterator last) {
range_initialize(first, last);
}
#else /* __STL_MEMBER_TEMPLATES */
list(const T* first, const T* last) { range_initialize(first, last); }
list(const_iterator first, const_iterator last) {
range_initialize(first, last);
}
#endif /* __STL_MEMBER_TEMPLATES */
list(const list<T, Alloc>& x) {
range_initialize(x.begin(), x.end());
}
~list() {
clear();
put_node(node);
}
list<T, Alloc>& operator=(const list<T, Alloc>& x);
protected:
void transfer(iterator position, iterator first, iterator last) {
if (position != last) {
(*(link_type((*last.node).prev))).next = position.node;
(*(link_type((*first.node).prev))).next = last.node;
(*(link_type((*position.node).prev))).next = first.node;
link_type tmp = link_type((*position.node).prev);
(*position.node).prev = (*last.node).prev;
(*last.node).prev = (*first.node).prev;
(*first.node).prev = tmp;
}
}
public:
void splice(iterator position, list& x) {
if (!x.empty())
transfer(position, x.begin(), x.end());
}
void splice(iterator position, list&, iterator i) {
iterator j = i;
++j;
if (position == i || position == j) return;
transfer(position, i, j);
}
void splice(iterator position, list&, iterator first, iterator last) {
if (first != last)
transfer(position, first, last);
}
void remove(const T& value);
void unique();
void merge(list& x);
void reverse();
void sort();
#ifdef __STL_MEMBER_TEMPLATES
template <class Predicate> void remove_if(Predicate);
template <class BinaryPredicate> void unique(BinaryPredicate);
template <class StrictWeakOrdering> void merge(list&, StrictWeakOrdering);
template <class StrictWeakOrdering> void sort(StrictWeakOrdering);
#endif /* __STL_MEMBER_TEMPLATES */
friend bool operator== __STL_NULL_TMPL_ARGS (const list& x, const list& y);
};
template <class T, class Alloc>
inline bool operator==(const list<T,Alloc>& x, const list<T,Alloc>& y) {
typedef typename list<T,Alloc>::link_type link_type;
link_type e1 = x.node;
link_type e2 = y.node;
link_type n1 = (link_type) e1->next;
link_type n2 = (link_type) e2->next;
for ( ; n1 != e1 && n2 != e2 ;
n1 = (link_type) n1->next, n2 = (link_type) n2->next)
if (n1->data != n2->data)
return false;
return n1 == e1 && n2 == e2;
}
template <class T, class Alloc>
inline bool operator<(const list<T, Alloc>& x, const list<T, Alloc>& y) {
return lexicographical_compare(x.begin(), x.end(), y.begin(), y.end());
}
#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER
template <class T, class Alloc>
inline void swap(list<T, Alloc>& x, list<T, Alloc>& y) {
x.swap(y);
}
#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */
#ifdef __STL_MEMBER_TEMPLATES
template <class T, class Alloc> template <class InputIterator>
void list<T, Alloc>::insert(iterator position,
InputIterator first, InputIterator last) {
for ( ; first != last; ++first)
insert(position, *first);
}
#else /* __STL_MEMBER_TEMPLATES */
template <class T, class Alloc>
void list<T, Alloc>::insert(iterator position, const T* first, const T* last) {
for ( ; first != last; ++first)
insert(position, *first);
}
template <class T, class Alloc>
void list<T, Alloc>::insert(iterator position,
const_iterator first, const_iterator last) {
for ( ; first != last; ++first)
insert(position, *first);
}
#endif /* __STL_MEMBER_TEMPLATES */
template <class T, class Alloc>
void list<T, Alloc>::insert(iterator position, size_type n, const T& x) {
for ( ; n > 0; --n)
insert(position, x);
}
template <class T, class Alloc>
list<T,Alloc>::iterator list<T, Alloc>::erase(iterator first, iterator last) {
while (first != last) erase(first++);
return last;
}
template <class T, class Alloc>
void list<T, Alloc>::resize(size_type new_size, const T& x)
{
iterator i = begin();
size_type len = 0;
for ( ; i != end() && len < new_size; ++i, ++len)
;
if (len == new_size)
erase(i, end());
else // i == end()
insert(end(), new_size - len, x);
}
template <class T, class Alloc>
void list<T, Alloc>::clear()
{
link_type cur = (link_type) node->next;
while (cur != node) {
link_type tmp = cur;
cur = (link_type) cur->next;
destroy_node(tmp);
}
node->next = node;
node->prev = node;
}
template <class T, class Alloc>
list<T, Alloc>& list<T, Alloc>::operator=(const list<T, Alloc>& x) {
if (this != &x) {
iterator first1 = begin();
iterator last1 = end();
const_iterator first2 = x.begin();
const_iterator last2 = x.end();
while (first1 != last1 && first2 != last2) *first1++ = *first2++;
if (first2 == last2)
erase(first1, last1);
else
insert(last1, first2, last2);
}
return *this;
}
template <class T, class Alloc>
void list<T, Alloc>::remove(const T& value) {
iterator first = begin();
iterator last = end();
while (first != last) {
iterator next = first;
++next;
if (*first == value) erase(first);
first = next;
}
}
template <class T, class Alloc>
void list<T, Alloc>::unique() {
iterator first = begin();
iterator last = end();
if (first == last) return;
iterator next = first;
while (++next != last) {
if (*first == *next)
erase(next);
else
first = next;
next = first;
}
}
template <class T, class Alloc>
void list<T, Alloc>::merge(list<T, Alloc>& x) {
iterator first1 = begin();
iterator last1 = end();
iterator first2 = x.begin();
iterator last2 = x.end();
while (first1 != last1 && first2 != last2)
if (*first2 < *first1) {
iterator next = first2;
transfer(first1, first2, ++next);
first2 = next;
}
else
++first1;
if (first2 != last2) transfer(last1, first2, last2);
}
template <class T, class Alloc>
void list<T, Alloc>::reverse() {
if (node->next == node || link_type(node->next)->next == node) return;
iterator first = begin();
++first;
while (first != end()) {
iterator old = first;
++first;
transfer(begin(), old, first);
}
}
template <class T, class Alloc>
void list<T, Alloc>::sort() {
if (node->next == node || link_type(node->next)->next == node) return;
list<T, Alloc> carry;
list<T, Alloc> counter[64];
int fill = 0;
while (!empty()) {
carry.splice(carry.begin(), *this, begin());
int i = 0;
while(i < fill && !counter[i].empty()) {
counter[i].merge(carry);
carry.swap(counter[i++]);
}
carry.swap(counter[i]);
if (i == fill) ++fill;
}
for (int i = 1; i < fill; ++i) counter[i].merge(counter[i-1]);
swap(counter[fill-1]);
}
#ifdef __STL_MEMBER_TEMPLATES
template <class T, class Alloc> template <class Predicate>
void list<T, Alloc>::remove_if(Predicate pred) {
iterator first = begin();
iterator last = end();
while (first != last) {
iterator next = first;
++next;
if (pred(*first)) erase(first);
first = next;
}
}
template <class T, class Alloc> template <class BinaryPredicate>
void list<T, Alloc>::unique(BinaryPredicate binary_pred) {
iterator first = begin();
iterator last = end();
if (first == last) return;
iterator next = first;
while (++next != last) {
if (binary_pred(*first, *next))
erase(next);
else
first = next;
next = first;
}
}
template <class T, class Alloc> template <class StrictWeakOrdering>
void list<T, Alloc>::merge(list<T, Alloc>& x, StrictWeakOrdering comp) {
iterator first1 = begin();
iterator last1 = end();
iterator first2 = x.begin();
iterator last2 = x.end();
while (first1 != last1 && first2 != last2)
if (comp(*first2, *first1)) {
iterator next = first2;
transfer(first1, first2, ++next);
first2 = next;
}
else
++first1;
if (first2 != last2) transfer(last1, first2, last2);
}
template <class T, class Alloc> template <class StrictWeakOrdering>
void list<T, Alloc>::sort(StrictWeakOrdering comp) {
if (node->next == node || link_type(node->next)->next == node) return;
list<T, Alloc> carry;
list<T, Alloc> counter[64];
int fill = 0;
while (!empty()) {
carry.splice(carry.begin(), *this, begin());
int i = 0;
while(i < fill && !counter[i].empty()) {
counter[i].merge(carry, comp);
carry.swap(counter[i++]);
}
carry.swap(counter[i]);
if (i == fill) ++fill;
}
for (int i = 1; i < fill; ++i) counter[i].merge(counter[i-1], comp);
swap(counter[fill-1]);
}
#endif /* __STL_MEMBER_TEMPLATES */
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma reset woff 1174
#endif
__STL_END_NAMESPACE
#endif /* __SGI_STL_INTERNAL_LIST_H */
// Local Variables:
// mode:C++
// End:
2.list的简单介绍
2.1实现list的类
我们在C语言实现的双向链表的实现中,我们需要有两个结构体,一个是结点的结构,另外一个是双向链表的结构。在C++list的实现中,则需要三个:
cpp
template <class T>
struct __list_node {
typedef void* void_pointer;
void_pointer next;
void_pointer prev;
T data;
};
template<class T, class Ref, class Ptr>
struct __list_iterator {
............};
template <class T, class Alloc = alloc>
class list {
............};
我们可以通过三个类的名字知道它们每个类的功能:
_list_node是结点,_list_iterator是迭代器,list则是双向链表。
2.2_list_iterator的实现
2.2.1_list_iterator实现的原因和好处
为什么要实现_list_iterator?
在我们C语言实现的双向链表中,我们需要访问其中所存的元素,可以用->,也可以用(*变量名).结构体所存变量这两个方式,比如:
cs
// 定义链表节点结构体
typedef struct Node {
int data; // 节点数据
struct Node* prev; // 指向前一个节点的指针
struct Node* next; // 指向下一个节点的指针
} Node;
int main() {
Node* head = NULL;
// 添加节点
//为了简化,我没有写这个函数了
appendNode(&head, 10);
appendNode(&head, 20);
appendNode(&head, 30);
// 演示 -> 和 (*). 两种访问方式
if (head != NULL) {
// 使用 -> 访问
printf("第一个节点的数据 (->): %d\n", head->data);
// 使用 (*). 访问
printf("第一个节点的数据 (*).: %d\n", (*head).data);
}
}
我们知道在list中,我们如果想要访问元素,那么就要用迭代器的方式,在我之前讲过的vector和string中,我们可以用下标+[]的方式来访问元素,其迭代器也可以用begin()+n的方式来访问元素,如果想要用迭代器,那么直接:typedef ...... iterator;typedef const ...... const_iterator;如果我们在链表中用这种方式,那么一定会报错的,因为如果我们这样写,就没法用->和*的方式了,而且我们如果直接用(*对象)的方式,那么就会出现很多问题:到底是用哪个东西进行typedef ...... iterator?就算是这样,我们可能还要存储里面的数据,如何访问?
如果我们用之前的那种方式就直接:typedef _list_node* iterator那么我们如果想要访问数据怎么办?
我们知道迭代器可以通过++来访问链表该元素的后一个数据,而这种方式那么是不能做到的。所以我们需要一个额外的类来typedef ...... iterator
这也说明一个问题:如果单纯用指针来做迭代器肯定是不行的,所以迭代器可以是指针的封装!
我们来看一下其中迭代器的实现:
cpp
template<class T, class Ref, class Ptr>
struct __list_iterator {
typedef __list_iterator<T, T&, T*> iterator;
typedef __list_iterator<T, const T&, const T*> const_iterator;
typedef __list_iterator<T, Ref, Ptr> self;
..................
};
首先我们可以发现这个iterator在_list_iterator中定义,首先要注意:Ref的意思是:引用(reference),Ptr的意思是:指针。其实这是为了存储多种的数据:如果我们仅仅存内置类型的数据,那么直接用这种方式确实是没有问题的,存储其他的数据就可能有问题了,一般我们是直接只有一个模板参数T,但是如果这种方式,那么就没办法typedef ...... const_iterator;因为const_iterator是不能修改的,而这样我们则需要重载一个额外的类_list_const_iterator,并且还要在list中typedef另外一个类的指针为const_iterator,这样写我们就需要额外拷贝一份实现差不多的类,相对麻烦,所以_list_iterator在实现时直接加了两个模板参数,相当于之后我们可以直接用这个模板类来生成两个类,实现方式很好,只不过我们理解起来比较麻烦了。总结下来就是这样写的好处有以下几个:
-
普通迭代器 (
iterator
):允许修改元素值(T&
和T*
) -
常量迭代器 (
const_iterator
):禁止修改元素值(const T&
和const T*
)
通过模板参数 Ref
和 Ptr
,可以用同一个 __list_iterator
模板生成两种迭代器:
cpp
typedef __list_iterator<T, T&, T*> iterator; // 可修改的迭代器
typedef __list_iterator<T, const T&, const T*> const_iterator; // 不可修改的迭代器
-
避免代码重复 :无需为
iterator
和const_iterator
分别写两个类,只需通过模板参数控制是否允许修改。 -
类型安全 :
const_iterator
会禁止用户通过它修改数据(编译器保证)。 -
通过模板参数传递
Ref
和Ptr
,可以确保: -
operator*()
返回Ref
(可能是T&
或const T&
)。 -
operator->()
返回Ptr
(可能是T*
或const T*
)。 -
在迭代器类中,解引用和箭头运算符的实现会依赖
Ref
和Ptr
可以简化代码:
-
在成员函数中,
self
直接表示当前迭代器类型。 -
例如在
operator++()
中,返回类型可以直接写self&
而非冗长的__list_iterator<T, Ref, Ptr>&
。
好处 | 说明 |
---|---|
代码复用 | 用同一个模板实现 iterator 和 const_iterator ,避免重复代码。 |
类型安全 | const_iterator 禁止修改数据,由编译器检查。 |
灵活性 | 可通过模板参数扩展迭代器行为(如代理迭代器)。 |
符合 STL 标准 | 提供统一的嵌套类型(如 reference 、pointer )。 |
清晰性 | 通过 self 别名简化代码,提高可读性。 |
这种设计是 STL 中迭代器实现的经典模式(如 GCC 的 std::list
源码),它平衡了类型安全、代码复用和泛型编程的需求。
2.2.2_list_iterator实现
由于该类是主要实现迭代器的功能的,也就没必要实现很多函数,基本上是运算符重载
cpp
bool operator==(const self& x) const { return node == x.node; }
bool operator!=(const self& x) const { return node != x.node; }
reference operator*() const { return (*node).data; }
pointer operator->() const { return &(operator*()); }
self& operator++() {
node = (link_type)((*node).next);
return *this;
}
self operator++(int) {
self tmp = *this;
++*this;
return tmp;
}
self& operator--() {
node = (link_type)((*node).prev);
return *this;
}
self operator--(int) {
self tmp = *this;
--*this;
return tmp;
}
这些函数的实现会在list的模拟实现中进行讲解,这里就不做很多讲解了。
2.3_list_node的实现
该类就比较简单了,就是存储一些指针以及数据而已,包括prev前驱指针、next后继指针、data锁存数据:
cpp
template <class T>
struct __list_node {
typedef void* void_pointer;
void_pointer next;
void_pointer prev;
T data;
};
我们要注意,这种方式很好(typedef void* void_pointer),我在这里只解释原因,以下是deepseek的搜索结果:
2.3.1. 避免递归的模板依赖
如果直接用 __list_node<T>*
定义指针:
cpp
template <class T>
struct __list_node {
__list_node<T>* next; // 类型依赖于模板参数 T
__list_node<T>* prev;
T data;
};
会导致 模板实例化时类型嵌套:
-
每次实例化
__list_node<T>
时,next
和prev
的类型会递归地依赖__list_node<T>
。 -
编译器需要为每一种
T
生成完整的__list_node<T>
类型(包括它的指针成员),可能增加编译时间和代码膨胀。
而使用 void*
:
cpp
typedef void* void_pointer;
void_pointer next; // 不直接依赖 T
void_pointer prev;
-
解耦指针类型 :
next
和prev
的类型与T
无关,仅是通用指针。 -
减少模板实例化的复杂度(所有
__list_node
的指针类型都是void*
,无论T
是什么)。
2.3.2. 内存布局一致性
void*
的尺寸在所有平台上通常是固定的(例如 4 字节或 8 字节,取决于系统):
-
无论
T
的类型如何,__list_node
的内存布局始终保持一致:[void* next][void* prev][T data]
-
如果使用
__list_node<T>*
,某些编译器可能会因模板实例化优化导致内存布局微调(尽管罕见)。
2.3.3. 类型安全的替代方案
虽然 void*
丢失了类型信息,但实际使用时会在迭代器中通过 static_cast
安全转换回 __list_node<T>*
:
cpp
// 在迭代器中的实际转换(例如 operator++)
node = static_cast<__list_node<T>*>(node->next);
-
类型安全 :由于链表是内部实现,开发者能保证
void*
实际指向的是__list_node<T>
,不会误用。 -
避免了模板递归带来的复杂性。
2.3.4. 与 C 风格链表的兼容性
void*
是 C 语言中通用指针的标准做法,这种设计:
-
可以更容易与 C 代码交互(例如跨语言传递链表节点)。
-
某些底层内存操作(如节点池分配器)可能直接操作
void*
指针。
2.3.5. 对比直接使用 __list_node<T>*
的缺点
如果直接用 __list_node<T>*
:
-
模板膨胀 :每个不同的
T
会实例化一个独立的__list_node<T>
类型,包括它的指针成员。 -
编译时间:模板实例化深度增加,可能影响编译速度。
-
调试符号膨胀 :调试信息中会为每种
T
生成完整的节点类型描述。
而 void*
实现:
- 所有
__list_node
的next/prev
类型相同,减少符号冗余。
2.3.6. STL 的实际实现示例
以 GCC 的 libstdc++
为例:
cpp
// 简化后的源码(GCC 13, bits/stl_list.h)
template <typename _Tp>
struct _List_node {
void* _M_next;
void* _M_prev;
_Tp _M_data;
};
- 实际使用时,通过
_List_iterator
迭代器将void*
转换回_List_node<_Tp>*
。
2.3.7为什么这种设计是安全的?
虽然 void*
看似放弃了类型安全,但在 STL 的实现中:
-
封装性 :
__list_node
是内部实现细节,用户代码不会直接操作它。 -
强制转换 :迭代器或链表方法会通过
static_cast
确保类型正确。 -
无裸露操作 :用户只能通过类型安全的接口(如
iterator
)访问链表。
总结:使用 void*
的原因
原因 | 说明 |
---|---|
模板解耦 | 避免 next/prev 指针类型依赖 T ,减少模板实例化复杂度。 |
内存一致性 | 所有 __list_node 的内存布局相同,与 T 无关。 |
性能优化 | 减少符号膨胀和编译时间。 |
底层控制 | 方便与 C 交互或实现内存池等底层操作。 |
安全性 | 通过封装和强制转换保证类型安全。 |
这种设计是 STL 在 类型抽象 和 性能优化 之间权衡的结果,体现了 C++ 模板元编程的典型技巧。
2.4list的实现
cpp
template <class T, class Alloc = alloc>
class list {
protected:
typedef void* void_pointer;
typedef __list_node<T> list_node;
typedef simple_alloc<list_node, Alloc> list_node_allocator;
public:
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef list_node* link_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
public:
typedef __list_iterator<T, T&, T*> iterator;
typedef __list_iterator<T, const T&, const T*> const_iterator;
#ifdef __STL_CLASS_PARTIAL_SPECIALIZATION
typedef reverse_iterator<const_iterator> const_reverse_iterator;
typedef reverse_iterator<iterator> reverse_iterator;
#else /* __STL_CLASS_PARTIAL_SPECIALIZATION */
typedef reverse_bidirectional_iterator<const_iterator, value_type,
const_reference, difference_type>
const_reverse_iterator;
typedef reverse_bidirectional_iterator<iterator, value_type, reference,
difference_type>
reverse_iterator;
}
可以在118-147行见到这些代码,我们主要还是看public部分,我们可以在iterator定义中知道,它其实就是_list_iterator这个类进行显式实例化来的,所以我们要注意这个iterator,因为之前我们在学习其他数据结构(容器)的时候,直接typedef T* iterator即可,这是需要注意的地方。
主要还是看这个成员函数:
cpp
iterator begin() { return (link_type)((*node).next); }
iterator end() { return node; }
reference front() { return *begin(); }
reference back() { return *(--end()); }
我们可以通过这些定义知道,这个双向循环链表的begin其实是尾结点解引用后的下一个结点,并且还要进行强制类型转换。
这个源码还是不要看太多了,我们主要是看它主要函数实现,其他的函数我将在下一讲讲解。
3.总结
list的实现源码还是比较复杂的,所以在之后的模拟实现中,可能会很难,但是,list使用确实也比较广泛,如果实在不理解模拟实现的还是建议了解一下,因为这个模拟实现主要还是为了提升我们的水平,以后面试可能要用到而已。
好了,这一讲就到这里,下一讲将进行讲解:list的模拟实现(难度较高)。喜欢的可以一键三连哦,下讲再见!
