C++拾遗--定位new表达式
前言
new表达式,默认下把内存开辟到堆区。使用定位new表达式,可以在指定地址区域(栈区、堆区、静态区)构造对象,这好比是把内存开辟到指定区域。
正文
定位new表达式的常见形式
- new(address) type;
- new(address) type(initializers);
- new(address) type[size];
- new(address) type[size]{braced initializer list};
定位new表达式调用 void *operator new(size_t, void *); 分配内存。
示例代码
#include <iostream> using namespace std; char addr1[100]; int main() { cout << "******定位new表达式演示***by David***" << endl; char addr2[100]; char *addr3 = new char[100]; cout << "addr1 = " << (void*)addr1 << endl; cout << "addr2 = " << (void*)addr2 << endl; cout << "addr3 = " << (void*)addr3 << endl; int *p = nullptr; //把内存分配到静态区 p = new(addr1)int; *p = 1; cout << (void*)p << " " << *p << endl; //把内存分配到栈区 p = new(addr2)int; *p = 2; cout << (void*)p << " " << *p << endl; //把内存分配到堆区 p = new(addr3)int; *p = 3; cout << (void*)p << " " << *p << endl; cin.get(); return 0; }
运行
本专栏目录
所有内容的目录
时间: 2024-12-29 17:41:34