以下文件目录均在/usr/include/c++/4.8/
中。
bits/allocator.h
文件中定义了stl默认使用的allocator。
line46: #include <bits/c++allocator.h> //Define the base class to std::allocator.
bits/c++allocator.h
中有如下代码:
#include <ext/new_allocator.h>
namespace std {
// An alias to the base class for std::allocator
// Used to set the std::allocator base class to _gnu_cxx::new_allocator
template<typename _Tp>
using __allocate_base = __gnu_cxx::new_allocator<_Tp>;
}
接下来就可以在<ext/new_allocator.h>
查看new_allocator
类的具体实现。
new_allocator
类中比较令人困惑的是成员rebind
的实现:
template<typename _Tp1>
struct rebind { using other = new_allocator<_Tp1>; }
查阅The C++ programming language
P998:
The curious rebind
template is an archaic(古老) alias. It should have been:
template<typename U>
using other = allocator<U>;
However, allocator
was defined before such aliases were supported by C++. It is provided to alllow an allocator to allocate objects of arbitrary type. Consider:
using Link_alloc = typename A::template rebind<Link>::other;
if A
is an allocator
, then rebind<Link>::other
is an alias for allocator<Link>
. For example:
template<typename T, typename A = allocator<T>>
class list {
private:
class Link { };
using Link_alloc = typename A::template rebind<Link>::other; // allocator<Link>
Link_alloc a; // link allocator
A alloc; // list allocator
};