其他分享
首页 > 其他分享> > 封装类(容器)中对 std::allocator 及 __gnu_cxx::__alloc_traits 的使用例

封装类(容器)中对 std::allocator 及 __gnu_cxx::__alloc_traits 的使用例

作者:互联网

#include <iostream>

class test {
  protected:
  	typedef int						int_type;
  	typedef std::string					str_type;
	
	typedef std::allocator<int_type>			_Int_alloc;
	typedef std::allocator<str_type>			_Str_alloc;
	
	typedef __gnu_cxx::__alloc_traits<_Int_alloc>		_Int_alloc_traits;
	typedef __gnu_cxx::__alloc_traits<_Str_alloc>		_Str_alloc_traits;
	
	typedef typename _Int_alloc::pointer		_Int_pointer;
	typedef typename _Str_alloc::pointer		_Str_pointer;
	
	struct test_impl : _Int_alloc, _Str_alloc {  };
	
	_Int_alloc&
	get_Int_allocator()
	{ return this->impl; }
	
	const _Int_alloc&
	get_Int_allocator() const
	{ return this->impl; }
	
	_Str_alloc&
	get_Str_allocator()
	{ return this->impl; }
	
	const _Str_alloc&
	get_Str_allocator() const
	{ return this->impl; }
	
	test_impl  impl;
	
  public:
	_Str_pointer
	get_str()
	{ return _Str_alloc_traits::allocate(get_Str_allocator(), 1); }
	
	void
	put_str(_Str_pointer __p)
	{ _Str_alloc_traits::deallocate(get_Str_allocator(), __p, 1); }
	
	_Int_pointer
	get_int()
	{ return _Int_alloc_traits::allocate(get_Int_allocator(), 1); }
	
	void
	put_int(_Int_pointer __p)
	{ _Int_alloc_traits::deallocate(get_Int_allocator(), __p, 1); }
	
	void
	construct_int(_Int_pointer __p, int_type __x)
	{ _Int_alloc_traits::construct(get_Int_allocator(), __p, __x); }
	
	void
	construct_str(_Str_pointer __p, str_type __x)
	{ _Str_alloc_traits::construct(get_Str_allocator(), __p, __x); }
	
	void
	destroy_int(_Int_pointer __p)
	{ _Int_alloc_traits::destroy(get_Int_allocator(), __p); }
	
	void
	destroy_str(_Str_pointer __p)
	{ _Str_alloc_traits::destroy(get_Str_allocator(), __p); }
};

signed main() {
	test		t;
	int*		ip = t.get_int();
	std::string*	sp = t.get_str();
	
	t.construct_int(ip, 114514);
	t.construct_str(sp, "1919810");
	
	std::cout << *ip << '\n' << *sp << '\n';
	
	t.destroy_int(ip);
	t.destroy_str(sp);
	
	t.put_int(ip);
	t.put_str(sp);
	
	return 0;
}

标签:__,std,alloc,get,Int,Str,allocator
来源: https://www.cnblogs.com/gyan083/p/16339974.html