【C++内存管理】3_placement new
文章目录
- placement new 允许我们将 object 构建于 allocated memory 中;
- 没有所谓 placement delete, 因为 placement new 根本没分配 memory;
亦或称呼与 placement new 对应的 operator delete 为 placement delete。
#include <new> char *buf = new char[sizeof(Complex) * 3]; Complex *pc = new(buf) Complex (1, 2); // ... delete[] buf;
Complex *pc = new(buf) Complex (1, 2);
编译器转换为 ==>
Complex *pc;
try {
void* mem = operator new (sizeof(Complex), buf); // allocate
pc = static_cast<Complex*>(mem); // cast
pc->Complex::Complex(1, 2); // construct
}
catch(std::bad_alloc) {
// 若 allocation 失败就不执行 constructor
}void* mem = operator new (sizeof(Complex), buf);
源码实现 ==>
void *operator new (size_t, viud *loc)
{
return loc;
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论