
毛利です。
C++Builder 10.2 Tokyo (Win64)を使って、
std::allocator<T>で 自分用のallocatorを作りstd::vector<T>などで利用する事ができます。
あまり知られていませんが std::vectorを見ると
template<class _Ty, class _Alloc = allocator<_Ty> >class vector{...}こうなっています。
第2引数を何も指定してなければstd::allocator<T>です。
まず、std::allocator<T>を継承したクラスを作成します。
//--------------------------------------------------------------------------- #include <functional> template <typename T> struct _Allocator: public std::allocator<T> { std::function<void(String)> _evt{[&](String _s){ Form1->Memo1->Lines->Append(_s); }}; _Allocator() { } _Allocator(const _Allocator& x) { } template<class T1>_Allocator(const _Allocator<T1>& x) { } T* allocate(size_t n, const T hint = 0) { if ( _evt != nullptr) _evt("allocate byte size=" + FloatToStr(n * sizeof(T))); return (T*) std::malloc(n * sizeof(T)); } void deallocate(T* ptr, size_t n) { if ( _evt != nullptr) _evt("free"); std::free(ptr); } template<class T1>struct rebind { typedef _Allocator<T1> other; }; };
作った自分用の_Allocatorをstd::vector<T>で使います。
/// void __fastcall TForm1::Button1Click(TObject *Sender) { Memo1->Lines->Clear(); Memo1->Lines->Append("------ byte ------"); std::vector<byte, _Allocator<byte>> vbyte{1}; Memo1->Lines->Append(""); Memo1->Lines->Append("------ long long ------"); std::vector<long long, _Allocator<long long>> vlonglong{1}; Memo1->Lines->Append(""); Memo1->Lines->Append("------ UnicodeString ------"); std::vector<UnicodeString, _Allocator<UnicodeString>> vUnicodeString{""}; Memo1->Lines->Append(""); }
実行します
自作したallocatorでMemo1にサイズを返しています。
なので、どれだけのメモリが確保されたのか確認できます。
Read More