一般在使用new 和 delete的时候,做了两件事情,一是空间的配置( new 是分配,delete是回收),而是调用对象的析构函数
但是也有办法将这两个过程分开
那就是显式的调用::operator new, ::operator delete,它们只进行空间配置,并不调用对象的析构函数
具体的可以参看下面这个例子:
// operator new[] example
#include <iostream> // std::cout
#include <new> // ::operator new[]
struct MyClass { int data;
MyClass() {std::cout << '*';} // print an asterisk for each construction
};
int main () {
std::cout << "constructions (1): "; // allocates and constructs five objects:
MyClass * p1 = new MyClass[5];
std::cout << '\n';
std::cout << "constructions (2): "; // allocates and constructs five objects (nothrow):
MyClass * p2 = new (std::nothrow) MyClass[5];
std::cout << '\n';
std::cout << "constructions (3): "; // allocates storage for five objects, but does not construct them:
MyClass * p3 = static_cast<MyClass*> (::operator new (sizeof(MyClass[5])));
std::cout << '\n';
std::cout << "constructions (4): "; // constructs five objects at p3, but does not allocate: new (p3) MyClass[5];
std::cout << '\n';
delete[] p3; delete[] p2; delete[] p1;
return 0;
}
|
|
关于operator delete和operator new ,可以参看这里的原型定义:
http://en.cppreference.com/w/cpp/memory/new/operator_delete
http://en.cppreference.com/w/cpp/memory/new/operator_new
可以看到,都是void*型的指针,跟C语言里面的malloc free机制差不多了。