C++ 在栈上使用 new
cpp
#include <iostream>
#include <cstdint>
using namespace std;
struct i64
{
i64() { cout << "i64 构造函数" << endl; }
~i64()
{
cout << "i64 析构函数" << endl;
first = 0;
second = 0;
}
uint32_t first = 0;
uint32_t second = 0;
};
int main()
{
uint32_t area[10] = {};
i64* cur = new(area) i64;
cur->first = 1111;
cur->second = 2222;
cout << "area[0]:" << area[0] << endl;
cout << "area[1]:" << area[1] << endl;
cout << "====================================" << endl;
area[0] = 2222;
area[1] = 1111;
cout << "(*cur).first :" << (*cur).first << endl;
cout << "(*cur).second:" << (*cur).second << endl;
// placement new 不需要 delete,内存管理由placement负责,但是需要显式调用析构函数
cur->~i64();
cur = nullptr;
cout << "area[0]:" << area[0] << endl;
cout << "area[1]:" << area[1] << endl;
// area属于局部变量,分配在栈上,会自动释放
return 0;
}
输出为
cpp
i64 构造函数
area[0]:1111
area[1]:2222
====================================
(*cur).first :2222
(*cur).second:1111
i64 析构函数
area[0]:0
area[1]:0