c++ new操作符
时间: 2023-11-24 18:48:09 浏览: 114
C++中的new操作符用于动态分配内存,它可以分配单个对象或者对象数组。在使用new操作符时,需要注意以下几点:
1. new操作符返回的是指向分配内存的指针,需要手动释放内存。
2. 如果分配内存失败,new操作符会抛出std::bad_alloc异常。
3. new操作符可以调用类的构造函数来初始化对象。
4. new操作符可以使用placement new来在已有的内存上构造对象。
5. new操作符可以重载,可以自定义内存分配策略。
下面是一些关于new操作符的例子:
1. 分配单个对象:
```
int* p = new int(10);
```
2. 分配对象数组:
```
int* arr = new int[10];
```
3. 使用placement new在已有的内存上构造对象:
```
void* buffer = ::operator new(sizeof(string));
string* p = new(buffer) string("hello");
```
4. 自定义内存分配策略:
```
void* operator new(size_t size) {
void* p = malloc(size);
if (!p) throw std::bad_alloc();
return p;
}
```
阅读全文
相关推荐


















