分配内存原理分配内存原理
union _Bxty
{ // storage for small buffer or pointer to larger one
_Elem _Buf[_BUF_SIZE];
_Elem *_Ptr;
char _Alias[_BUF_SIZE]; // to permit aliasing
} _Bx;
这个_Bxty是一个union。当分配字符串所需内存小于_BUF_SIZE,_Buf存放我们的字符串,当然也不一定是字符串,也可以放int数组这种东西。当分配内存大于_BUF_SIZE,_Ptr由内存分配器_ALLOCATOR分配,然后存放我们的字符串。
类构成关系
typedef basic_string<char, char_traits<char>, allocator<char> > string;
template<class _Elem>
struct char_traits
: public _Char_traits<_Elem, long>
{ // properties of a string or stream unknown element
};
xmemory文件:
#define _ALLOCATOR allocator
template<class _Ty>
class _ALLOCATOR
: public _Allocator_base<_Ty>
{ // generic allocator for objects of class _Ty
...
}
// TEMPLATE CLASS basic_string
template<class _Elem,
class _Traits,
class _Ax>
class basic_string
: public _String_val<_Elem, _Ax>
{ // null-terminated transparent array of elements
...
}
// TEMPLATE CLASS _String_val
template<class _Elem,
class _Alloc>
class _String_val
: public _Container_base
{ // base class for basic_string to hold data
...
union _Bxty
{ // storage for small buffer or pointer to larger one
_Elem _Buf[_BUF_SIZE];
_Elem *_Ptr;
char _Alias[_BUF_SIZE]; // to permit aliasing
} _Bx;
size_type _Mysize; // current length of string
size_type _Myres; // current storage reserved for string
_Alty _Alval; // allocator object for strings
}
typedef _Container_base12 _Container_base;
struct _CRTIMP2_PURE _Container_base12
{ // store pointer to _Container_proxy
...
}
从实例构造说起
string str5("abcdefghijklmn12345");
string str("abc");
str = "abcdefghijklmn12345";
basic_string(const _Elem *_Ptr)
: _Mybase()
{ // construct from [_Ptr, <null>)
_Tidy();
assign(_Ptr);
}
_String_val(_Alty _Al = _Alty())
: _Alval(_Al)
{ // construct allocator from _Al
typename _Alloc::template rebind<_Container_proxy>::other
_Alproxy(_Alval