VS2010 std::string 源码分析

分配内存原理分配内存原理

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值