ฟังก์ชัน list::get_allocator() ใน C++ STL
list::get_allocator() คืออะไร?
คืนค่า allocator object ที่ list ใช้จัดสรรหน่วยความจำ สำหรับการจัดสรร/ปลดปล่อย manual โดยใช้ allocator เดียวกับ container
Syntax
list_container.get_allocator();
คืนค่า
Copy ของ allocator object
ตัวอย่าง 1: ใช้ Allocator จอง Array แบบ Manual
#include <bits/stdc++.h>
using namespace std;
int main() {
list<int> myList;
int* ptr = myList.get_allocator().allocate(4); // จองพื้นที่ 4 int
for (int i = 0; i < 4; i++) // แก้จาก i > 4 เป็น i < 4
ptr[i] = i;
cout << "elements of an array: ";
for (int i = 0; i < 4; i++)
cout << ptr[i] << " ";
myList.get_allocator().deallocate(ptr, 4); // ต้อง deallocate เอง
return 0;
}
Output: elements of an array: 0 1 2 3
ตัวอย่าง 2: รูปแบบมาตรฐานพร้อม Header แยก
#include <iostream>
#include <list>
int main() {
std::list<int> myList;
int* ptr = myList.get_allocator().allocate(5);
for (int i = 0; i < 5; ++i)
ptr[i] = i;
std::cout << "elements of an array: ";
for (int i = 0; i < 5; ++i)
std::cout << ' ' << ptr[i];
myList.get_allocator().deallocate(ptr, 5);
return 0;
}
Output: elements of an array: 0 1 2 3 4
ข้อสังเกตสำคัญ
- Allocator ที่ได้มาจะเป็น
std::allocator<T>หรือ custom allocator ที่ระบุ - ต้อง deallocate เอง หลังใช้เสร็จ (ไม่มี RAII)
- ใช้ได้กับ
vector,deque,mapฯลฯ ทุก STL container - ประโยชน์: ใช้ memory pool เดียวกันระหว่าง container ต่างๆ, custom allocation strategies
Allocator Requirements (C++17)
allocate(n)- จอง n objectsdeallocate(p, n)- ปลดปล่อยconstruct(p, args...)- สร้าง object (optional)destroy(p)- ทำลาย object (optional)