Skip to content

Instantly share code, notes, and snippets.

@buyoh
Last active August 17, 2018 16:16
Show Gist options
  • Save buyoh/a00bb04e80cd6be63587c614f3c99aa4 to your computer and use it in GitHub Desktop.
Save buyoh/a00bb04e80cd6be63587c614f3c99aa4 to your computer and use it in GitHub Desktop.
std::allocator と std::allocator_traits のメモ
#pragma GCC optimize ("O3")
#include "bits/stdc++.h"
using namespace std;
struct S{
int x;
S(int _x = 0):x(_x){
cout << "con" << x << ";" << this << endl;
}
S& operator=(S&& s){
x = s.x;
cout << "move"<< x << ";" << this << "<=" << &s << endl;
}
~S(){
cout << "del" << x << ";" << this << endl;
}
};
int main(){
allocator<S> alloc;
// allocator_traitsを使うようにする
using tr = allocator_traits<decltype(alloc)>;
// メモリ確保
auto* sushi = tr::allocate(alloc, 5);
cout << "&sushi: " << sushi << endl;
// 直接構築 確保したメモリ上でコンストラクタを呼ぶ
tr::construct(alloc, sushi+0, 10);
// ムーヴ構築 (ムーヴ関数があれば)確保したメモリ上でコンストラクタは呼ばれない
sushi[1] = S(12);
// デストラクタを呼ぶ メモリは開放しない
tr::destroy(alloc, sushi+0);
tr::destroy(alloc, sushi+1);
// メモリを開放する デストラクタは呼ばない
tr::deallocate(alloc, sushi, 5);
return 0;
}
/*
stdout
&sushi: 0x6000283d0
con10;0x6000283d0
con12;0xffffcbbc
move12;0x6000283d4<=0xffffcbbc
del12;0xffffcbbc
del10;0x6000283d0
del12;0x6000283d4
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment