get_temporar_buffer یک حافظه موقت بدون مقدار اولیه و صدا زدن سازنده کلاس برای ما می گیره.
تفاوتی که با new داره اینه که در صورت نبود حافظه کافی new یک exception برمیگردونه و در صورت catch نشدن برنامه بسته میشه ولی این تابع هر قدر که امکان باشه (یعنی کمتر از مقدار مورد نیاز )حافظه بر میگردونه . و به عنوان نمونه برای ساختن memory pool میتونه مورد استفاده قرار بگیره .
خروجی این تابع یک pair از حافظه برگشت داده شده به همراه سایز هست
مثال :
#include <iostream>
#include <string>
#include <memory>
int main() {
const ptrdiff_t size = 100000000;
std::pair<std::string*,std::ptrdiff_t> mem=std::get_temporary_buffer<std::string>(size);
if (mem.second==0){//hafeze natoneste begire
std::cout << "Can not allocate memory\n";
}
else if (mem.second < size){//memory be anaze kafi gerefte nashode
std::cout << "Not enough memory Just allocate : "<<mem.second<<"\n";
//use mem.first
//...
std::return_temporary_buffer<std::string>(mem.first);
}
else{//hafeze be dorosti gerefte shode
std::cout << "Memory allocation was successful\n";
//use mem.first
//...
std::return_temporary_buffer<std::string>(mem.first);
}
}