Updated:

1 minute read

개요

  • destroy
    • 범위의 객체를 파괴
  • destroy_at
    • 객체를 파괴
  • destroy_n
    • 범위의 시작부터 n개의 객체를 파괴


예제

  • 코드
     #include <iostream>
     #include <memory>
        
     using namespace std;
        
     class Test {
     	private:
     		// int i;
        
     	public:
     		int i;
        
     		Test(int i) : i(i) {}
     		~Test() { cout << "~Test() : " << this->i << endl; }
     };
        
     void destroy_test() {
     	cout << __func__ << " start" << endl;
        
     	constexpr int size = 3;
        
     	unsigned char pool[sizeof(Test) * size];
        
     	for (int i = 0; i < size; ++i) {
     		new (pool + (sizeof(Test) * i)) Test(i);
     	}
        
     	auto ptr = launder(reinterpret_cast<Test *>(pool));
        
     	destroy(ptr, ptr + size);
        
     	cout << __func__ << " end" << endl;
     }
        
     void destroy_at_test() {
     	cout << __func__ << " start" << endl;
        
     	constexpr int size = 3;
        
     	unsigned char pool[sizeof(Test) * size];
        
     	for (int i = 0; i < size; ++i) {
     		new (pool + (sizeof(Test) * i)) Test(i);
     	}
        
     	auto ptr = launder(reinterpret_cast<Test *>(pool));
        
     	for (int i = 0; i < size; ++i) {
     		destroy_at(ptr + i);
     	}
        
     	cout << __func__ << " end" << endl;
     }
        
     void destroy_n_test() {
     	cout << __func__ << " start" << endl;
        
     	constexpr int size = 3;
        
     	unsigned char pool[sizeof(Test) * size];
        
     	for (int i = 0; i < size; ++i) {
     		new (pool + (sizeof(Test) * i)) Test(i);
     	}
        
     	auto ptr = launder(reinterpret_cast<Test *>(pool));
        
     	destroy_n(ptr, size);
        
     	cout << __func__ << " end" << endl;
     }
        
     int main() {
     	destroy_test();
        
     	cout << endl;
        
     	destroy_at_test();
        
     	cout << endl;
        
     	destroy_n_test();
        
     	return 0;
     }
    
  • 실행 결과
     destroy_test start
     ~Test() : 0
     ~Test() : 1
     ~Test() : 2
     destroy_test end
        
     destroy_at_test start
     ~Test() : 0
     ~Test() : 1
     ~Test() : 2
     destroy_at_test end
        
     destroy_n_test start
     ~Test() : 0
     ~Test() : 1
     ~Test() : 2
     destroy_n_test end