c++stl源码(一)

写这篇文章的原因,希望自己能在技术的道路上越走越远,在一年前使用c语言写了些数据结构后,学会了使用工具的stl,但是希望自己能在源码上对自己使用的stl更加的深入了解,由于本人的学识浅薄,如有错误,还望摘正

首先我们要有stl source code 不要从别的网站下载我们使用github 打开自己的文件后

git clone https://github.com/gcc-mirror/gcc

如果没有安装git使用上述的网站即可

打开gcc-master后 然后我们的目光聚焦在libstdc++-v3文件夹里的内容(个人认为 可能不对:) )

文件夹的内容很多诸如我们先看std文件夹里面有许多文件,我们先看大家最熟悉的vector

#ifndef _GLIBCXX_VECTOR
#define _GLIBCXX_VECTOR 1

#pragma GCC system_header

#include <bits/stl_algobase.h>
#include <bits/allocator.h>
#include <bits/stl_construct.h>
#include <bits/stl_uninitialized.h>
#include <bits/stl_vector.h>
#include <bits/stl_bvector.h>
#include <bits/range_access.h>

#ifndef _GLIBCXX_EXPORT_TEMPLATE
# include <bits/vector.tcc>
#endif

#ifdef _GLIBCXX_DEBUG
# include <debug/vector>
#endif

#ifdef _GLIBCXX_PROFILE
# include <profile/vector>
#endif

#endif /* _GLIBCXX_VECTOR */

可以看到我们平时写代码时候#include< vector >(不应该在<>中加空格但是我因为排版问题加了)时候实际上是包含了很多bits中的头文件

#ifndef _GLIBCXX_VECTOR
#define _GLIBCXX_VECTOR 1

....

#ifndef _GLIBCXX_EXPORT_TEMPLATE
# include <bits/vector.tcc>
#endif

#ifdef _GLIBCXX_DEBUG
# include <debug/vector>
#endif

#ifdef _GLIBCXX_PROFILE
# include <profile/vector>
#endif

#endif
一部分代码都是 宏保护

以防万一贴一个比较好的解释,因为不这么做可能会导致一个编译错误
为什么要宏保护
我再简单解释下主要是 防止一个头文件被包含两次,导致重复的定义而引起的编译错误

#pragma GCC system_header

解释

#include <bits/stl_algobase.h>
#include <bits/allocator.h>
#include <bits/stl_construct.h>
#include <bits/stl_uninitialized.h>
#include <bits/stl_vector.h>
#include <bits/stl_bvector.h>
#include <bits/range_access.h>
这些是真正实现 vector 的代码限于篇幅我们分开看

猜你喜欢

转载自blog.csdn.net/weixin_38739799/article/details/80722634
今日推荐