当前位置: 首页 > article >正文

C++初阶-list的底层

目录

1.std::list实现的所有代码

2.list的简单介绍

2.1实现list的类

2.2_list_iterator的实现

2.2.1_list_iterator实现的原因和好处

2.2.2_list_iterator实现

2.3_list_node的实现

2.3.1. 避免递归的模板依赖

2.3.2. 内存布局一致性

2.3.3. 类型安全的替代方案

2.3.4. 与 C 风格链表的兼容性

2.3.5. 对比直接使用 __list_node * 的缺点

2.3.6. STL 的实际实现示例

2.3.7为什么这种设计是安全的?

总结:使用 void* 的原因

2.4list的实现

3.总结



1.std::list实现的所有代码

这是std::list函数的基本实现,一共有617行,如果不想看的话可以去到2,我会解释一部分:

/*** 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
#endiftemplate <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_OPERATORpointer 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_SPECIALIZATIONtemplate <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_SPECIALIZATIONtypedef 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_TEMPLATEStemplate <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_TEMPLATEStemplate <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_TEMPLATEStemplate <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_TEMPLATEStemplate <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_ORDERtemplate <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_TEMPLATEStemplate <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);elseinsert(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);elsefirst = 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_TEMPLATEStemplate <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);elsefirst = 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的实现中,则需要三个:

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语言实现的双向链表中,我们需要访问其中所存的元素,可以用->,也可以用(*变量名).结构体所存变量这两个方式,比如:

// 定义链表节点结构体
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

这也说明一个问题:如果单纯用指针来做迭代器肯定是不行的,所以迭代器可以是指针的封装!

我们来看一下其中迭代器的实现:

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 模板生成两种迭代器:

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 标准提供统一的嵌套类型(如 referencepointer)。
清晰性通过 self 别名简化代码,提高可读性。

这种设计是 STL 中迭代器实现的经典模式(如 GCC 的 std::list 源码),它平衡了类型安全、代码复用和泛型编程的需求。

2.2.2_list_iterator实现

由于该类是主要实现迭代器的功能的,也就没必要实现很多函数,基本上是运算符重载

 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锁存数据:

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>* 定义指针:

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*

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>*

// 在迭代器中的实际转换(例如 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++ 为例:

// 简化后的源码(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 的实现中:

  1. 封装性__list_node 是内部实现细节,用户代码不会直接操作它。

  2. 强制转换:迭代器或链表方法会通过 static_cast 确保类型正确。

  3. 无裸露操作:用户只能通过类型安全的接口(如 iterator)访问链表。

总结:使用 void* 的原因

原因说明
模板解耦避免 next/prev 指针类型依赖 T,减少模板实例化复杂度。
内存一致性所有 __list_node 的内存布局相同,与 T 无关。
性能优化减少符号膨胀和编译时间。
底层控制方便与 C 交互或实现内存池等底层操作。
安全性通过封装和强制转换保证类型安全。

这种设计是 STL 在 类型抽象 和 性能优化 之间权衡的结果,体现了 C++ 模板元编程的典型技巧。

2.4list的实现

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_SPECIALIZATIONtypedef 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即可,这是需要注意的地方。

主要还是看这个成员函数:

 iterator begin() { return (link_type)((*node).next); }iterator end() { return node; }reference front() { return *begin(); }reference back() { return *(--end()); }

我们可以通过这些定义知道,这个双向循环链表的begin其实是尾结点解引用后的下一个结点,并且还要进行强制类型转换。

这个源码还是不要看太多了,我们主要是看它主要函数实现,其他的函数我将在下一讲讲解。

3.总结

list的实现源码还是比较复杂的,所以在之后的模拟实现中,可能会很难,但是,list使用确实也比较广泛,如果实在不理解模拟实现的还是建议了解一下,因为这个模拟实现主要还是为了提升我们的水平,以后面试可能要用到而已。

好了,这一讲就到这里,下一讲将进行讲解:list的模拟实现(难度较高)。喜欢的可以一键三连哦,下讲再见!

相关文章:

C++初阶-list的底层

目录 1.std::list实现的所有代码 2.list的简单介绍 2.1实现list的类 2.2_list_iterator的实现 2.2.1_list_iterator实现的原因和好处 2.2.2_list_iterator实现 2.3_list_node的实现 2.3.1. 避免递归的模板依赖 2.3.2. 内存布局一致性 2.3.3. 类型安全的替代方案 2.3.…...

【kafka】Golang实现分布式Masscan任务调度系统

要求&#xff1a; 输出两个程序&#xff0c;一个命令行程序&#xff08;命令行参数用flag&#xff09;和一个服务端程序。 命令行程序支持通过命令行参数配置下发IP或IP段、端口、扫描带宽&#xff0c;然后将消息推送到kafka里面。 服务端程序&#xff1a; 从kafka消费者接收…...

iOS 26 携众系统重磅更新,但“苹果智能”仍与国行无缘

美国西海岸的夏天&#xff0c;再次被苹果点燃。一年一度的全球开发者大会 WWDC25 如期而至&#xff0c;这不仅是开发者的盛宴&#xff0c;更是全球数亿苹果用户翘首以盼的科技春晚。今年&#xff0c;苹果依旧为我们带来了全家桶式的系统更新&#xff0c;包括 iOS 26、iPadOS 26…...

TDengine 快速体验(Docker 镜像方式)

简介 TDengine 可以通过安装包、Docker 镜像 及云服务快速体验 TDengine 的功能&#xff0c;本节首先介绍如何通过 Docker 快速体验 TDengine&#xff0c;然后介绍如何在 Docker 环境下体验 TDengine 的写入和查询功能。如果你不熟悉 Docker&#xff0c;请使用 安装包的方式快…...

【Linux】shell脚本忽略错误继续执行

在 shell 脚本中&#xff0c;可以使用 set -e 命令来设置脚本在遇到错误时退出执行。如果你希望脚本忽略错误并继续执行&#xff0c;可以在脚本开头添加 set e 命令来取消该设置。 举例1 #!/bin/bash# 取消 set -e 的设置 set e# 执行命令&#xff0c;并忽略错误 rm somefile…...

stm32G473的flash模式是单bank还是双bank?

今天突然有人stm32G473的flash模式是单bank还是双bank&#xff1f;由于时间太久&#xff0c;我真忘记了。搜搜发现&#xff0c;还真有人和我一样。见下面的链接&#xff1a;https://shequ.stmicroelectronics.cn/forum.php?modviewthread&tid644563 根据STM32G4系列参考手…...

springboot 百货中心供应链管理系统小程序

一、前言 随着我国经济迅速发展&#xff0c;人们对手机的需求越来越大&#xff0c;各种手机软件也都在被广泛应用&#xff0c;但是对于手机进行数据信息管理&#xff0c;对于手机的各种软件也是备受用户的喜爱&#xff0c;百货中心供应链管理系统被用户普遍使用&#xff0c;为方…...

调用支付宝接口响应40004 SYSTEM_ERROR问题排查

在对接支付宝API的时候&#xff0c;遇到了一些问题&#xff0c;记录一下排查过程。 Body:{"datadigital_fincloud_generalsaas_face_certify_initialize_response":{"msg":"Business Failed","code":"40004","sub_msg…...

Linux链表操作全解析

Linux C语言链表深度解析与实战技巧 一、链表基础概念与内核链表优势1.1 为什么使用链表&#xff1f;1.2 Linux 内核链表与用户态链表的区别 二、内核链表结构与宏解析常用宏/函数 三、内核链表的优点四、用户态链表示例五、双向循环链表在内核中的实现优势5.1 插入效率5.2 安全…...

智慧医疗能源事业线深度画像分析(上)

引言 医疗行业作为现代社会的关键基础设施,其能源消耗与环境影响正日益受到关注。随着全球"双碳"目标的推进和可持续发展理念的深入,智慧医疗能源事业线应运而生,致力于通过创新技术与管理方案,重构医疗领域的能源使用模式。这一事业线融合了能源管理、可持续发…...

Lombok 的 @Data 注解失效,未生成 getter/setter 方法引发的HTTP 406 错误

HTTP 状态码 406 (Not Acceptable) 和 500 (Internal Server Error) 是两类完全不同的错误&#xff0c;它们的含义、原因和解决方法都有显著区别。以下是详细对比&#xff1a; 1. HTTP 406 (Not Acceptable) 含义&#xff1a; 客户端请求的内容类型与服务器支持的内容类型不匹…...

应用升级/灾备测试时使用guarantee 闪回点迅速回退

1.场景 应用要升级,当升级失败时,数据库回退到升级前. 要测试系统,测试完成后,数据库要回退到测试前。 相对于RMAN恢复需要很长时间&#xff0c; 数据库闪回只需要几分钟。 2.技术实现 数据库设置 2个db_recovery参数 创建guarantee闪回点&#xff0c;不需要开启数据库闪回。…...

论文解读:交大港大上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化学习框架(二)

HoST框架核心实现方法详解 - 论文深度解读(第二部分) 《Learning Humanoid Standing-up Control across Diverse Postures》 系列文章: 论文深度解读 + 算法与代码分析(二) 作者机构: 上海AI Lab, 上海交通大学, 香港大学, 浙江大学, 香港中文大学 论文主题: 人形机器人…...

微信小程序之bind和catch

这两个呢&#xff0c;都是绑定事件用的&#xff0c;具体使用有些小区别。 官方文档&#xff1a; 事件冒泡处理不同 bind&#xff1a;绑定的事件会向上冒泡&#xff0c;即触发当前组件的事件后&#xff0c;还会继续触发父组件的相同事件。例如&#xff0c;有一个子视图绑定了b…...

ES6从入门到精通:前言

ES6简介 ES6&#xff08;ECMAScript 2015&#xff09;是JavaScript语言的重大更新&#xff0c;引入了许多新特性&#xff0c;包括语法糖、新数据类型、模块化支持等&#xff0c;显著提升了开发效率和代码可维护性。 核心知识点概览 变量声明 let 和 const 取代 var&#xf…...

RocketMQ延迟消息机制

两种延迟消息 RocketMQ中提供了两种延迟消息机制 指定固定的延迟级别 通过在Message中设定一个MessageDelayLevel参数&#xff0c;对应18个预设的延迟级别指定时间点的延迟级别 通过在Message中设定一个DeliverTimeMS指定一个Long类型表示的具体时间点。到了时间点后&#xf…...

CTF show Web 红包题第六弹

提示 1.不是SQL注入 2.需要找关键源码 思路 进入页面发现是一个登录框&#xff0c;很难让人不联想到SQL注入&#xff0c;但提示都说了不是SQL注入&#xff0c;所以就不往这方面想了 ​ 先查看一下网页源码&#xff0c;发现一段JavaScript代码&#xff0c;有一个关键类ctfs…...

docker详细操作--未完待续

docker介绍 docker官网: Docker&#xff1a;加速容器应用程序开发 harbor官网&#xff1a;Harbor - Harbor 中文 使用docker加速器: Docker镜像极速下载服务 - 毫秒镜像 是什么 Docker 是一种开源的容器化平台&#xff0c;用于将应用程序及其依赖项&#xff08;如库、运行时环…...

java_网络服务相关_gateway_nacos_feign区别联系

1. spring-cloud-starter-gateway 作用&#xff1a;作为微服务架构的网关&#xff0c;统一入口&#xff0c;处理所有外部请求。 核心能力&#xff1a; 路由转发&#xff08;基于路径、服务名等&#xff09;过滤器&#xff08;鉴权、限流、日志、Header 处理&#xff09;支持负…...

label-studio的使用教程(导入本地路径)

文章目录 1. 准备环境2. 脚本启动2.1 Windows2.2 Linux 3. 安装label-studio机器学习后端3.1 pip安装(推荐)3.2 GitHub仓库安装 4. 后端配置4.1 yolo环境4.2 引入后端模型4.3 修改脚本4.4 启动后端 5. 标注工程5.1 创建工程5.2 配置图片路径5.3 配置工程类型标签5.4 配置模型5.…...

利用ngx_stream_return_module构建简易 TCP/UDP 响应网关

一、模块概述 ngx_stream_return_module 提供了一个极简的指令&#xff1a; return <value>;在收到客户端连接后&#xff0c;立即将 <value> 写回并关闭连接。<value> 支持内嵌文本和内置变量&#xff08;如 $time_iso8601、$remote_addr 等&#xff09;&a…...

CVPR 2025 MIMO: 支持视觉指代和像素grounding 的医学视觉语言模型

CVPR 2025 | MIMO&#xff1a;支持视觉指代和像素对齐的医学视觉语言模型 论文信息 标题&#xff1a;MIMO: A medical vision language model with visual referring multimodal input and pixel grounding multimodal output作者&#xff1a;Yanyuan Chen, Dexuan Xu, Yu Hu…...

python打卡day49

知识点回顾&#xff1a; 通道注意力模块复习空间注意力模块CBAM的定义 作业&#xff1a;尝试对今天的模型检查参数数目&#xff0c;并用tensorboard查看训练过程 import torch import torch.nn as nn# 定义通道注意力 class ChannelAttention(nn.Module):def __init__(self,…...

基于FPGA的PID算法学习———实现PID比例控制算法

基于FPGA的PID算法学习 前言一、PID算法分析二、PID仿真分析1. PID代码2.PI代码3.P代码4.顶层5.测试文件6.仿真波形 总结 前言 学习内容&#xff1a;参考网站&#xff1a; PID算法控制 PID即&#xff1a;Proportional&#xff08;比例&#xff09;、Integral&#xff08;积分&…...

<6>-MySQL表的增删查改

目录 一&#xff0c;create&#xff08;创建表&#xff09; 二&#xff0c;retrieve&#xff08;查询表&#xff09; 1&#xff0c;select列 2&#xff0c;where条件 三&#xff0c;update&#xff08;更新表&#xff09; 四&#xff0c;delete&#xff08;删除表&#xf…...

大话软工笔记—需求分析概述

需求分析&#xff0c;就是要对需求调研收集到的资料信息逐个地进行拆分、研究&#xff0c;从大量的不确定“需求”中确定出哪些需求最终要转换为确定的“功能需求”。 需求分析的作用非常重要&#xff0c;后续设计的依据主要来自于需求分析的成果&#xff0c;包括: 项目的目的…...

云计算——弹性云计算器(ECS)

弹性云服务器&#xff1a;ECS 概述 云计算重构了ICT系统&#xff0c;云计算平台厂商推出使得厂家能够主要关注应用管理而非平台管理的云平台&#xff0c;包含如下主要概念。 ECS&#xff08;Elastic Cloud Server&#xff09;&#xff1a;即弹性云服务器&#xff0c;是云计算…...

51c自动驾驶~合集58

我自己的原文哦~ https://blog.51cto.com/whaosoft/13967107 #CCA-Attention 全局池化局部保留&#xff0c;CCA-Attention为LLM长文本建模带来突破性进展 琶洲实验室、华南理工大学联合推出关键上下文感知注意力机制&#xff08;CCA-Attention&#xff09;&#xff0c;…...

Prompt Tuning、P-Tuning、Prefix Tuning的区别

一、Prompt Tuning、P-Tuning、Prefix Tuning的区别 1. Prompt Tuning(提示调优) 核心思想:固定预训练模型参数,仅学习额外的连续提示向量(通常是嵌入层的一部分)。实现方式:在输入文本前添加可训练的连续向量(软提示),模型只更新这些提示参数。优势:参数量少(仅提…...

树莓派超全系列教程文档--(61)树莓派摄像头高级使用方法

树莓派摄像头高级使用方法 配置通过调谐文件来调整相机行为 使用多个摄像头安装 libcam 和 rpicam-apps依赖关系开发包 文章来源&#xff1a; http://raspberry.dns8844.cn/documentation 原文网址 配置 大多数用例自动工作&#xff0c;无需更改相机配置。但是&#xff0c;一…...