1. 迭代器的本質
(1) 標準要求
-
C++ 標準要求?
std::string
?和?std::vector
?的迭代器必須是?隨機訪問迭代器(Random Access Iterator)。 -
指針天然滿足隨機訪問迭代器的所有操作(如?
++
、--
、+n
、*
?等),因此可以直接用指針實現。
(2) 典型定義
cpp
// vector 和 string 的迭代器通常類似以下形式 typedef T* iterator; // 非常量迭代器 typedef const T* const_iterator; // 常量迭代器
2. MSVC 的實現
(1)?std::vector
?迭代器
-
直接使用指針:
cpp
template<class T> class vector { public:typedef T* iterator;typedef const T* const_iterator;// ... };
-
Debug 模式增強:
-
在 Debug 模式下,MSVC 會用封裝類(如?
_Checked_iterator
)包裹指針,添加邊界檢查和迭代器校驗。
-
(2)?std::string
?迭代器
-
類似?
vector
:cpp
typedef char* iterator; // 非常量迭代器 typedef const char* const_iterator;
-
Debug 模式:
-
同樣會封裝為安全迭代器,防止越界訪問。
-
3. GCC 的實現
(1)?std::vector
?迭代器
-
直接使用指針:
cpp
template<class T>class vector {public:typedef T* iterator; typedef const T* const_iterator;// ... };
-
無 Debug 封裝:
-
GCC 默認不添加調試校驗,迭代器就是原生指針。
-
(2)?std::string
?迭代器
-
依賴 SSO 實現:
-
短字符串(SSO):迭代器指向內部緩沖區(如?
_M_p
)。 -
長字符串:迭代器指向堆內存。
cpp
typedef char* iterator; typedef const char* const_iterator;
-
4. 關鍵差異
特性 | MSVC | GCC |
---|---|---|
迭代器類型 | 指針或調試封裝類 | 直接使用指針 |
Debug 校驗 | 有(防止越界和失效迭代器) | 無 |
性能影響 | Debug 模式較慢,Release 無差異 | 始終高效 |