new/delete
string *ps=new string("hello");
delete ps;
new表达式实际上执行了三步操作:
- 调用operator new标准库函数分配内存空间
- 运行string类的构造函数构造对象
- 返回指向该对象的指针
delete表达式实际上执行了两步操作:
- 调用ps所指对象的析构函数
- 调用operator delete标准库函数释放内存空间
operator new/operator delete
一般我们说重载new和delete,实际上是重载operator new和operator delete库函数。new和delete表达式不允许重载。
默认情况下,new/delete表达式使用的是全局的(编译器默认的)operator new/operator delete函数。我们可以定义自己实现的operator new和operator delete函数。
标准库中定义了operator new/operatordelete的8个重载版本。
//可能抛出异常
void *operator new(size_t);
void *operator new[](size_t);
void operator delete(void *) noexcept;
void operator delete[](void *) noexcept;
//承诺不会抛出异常
void *operator new(size_t, nothrow_t &) noexcept;
void *operator new[](size_t, nothrow_t &) noexcept;
void operator delete(void *, nothrow_t &) noexcept;
void operator delete[](void *, nothrow_t &)noexcept;
注意:void operator new(size_t, void )形式不允许用户重新定义,只供标准库使用。
测试代码:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class A
{
public:
A(string s) : _s(s)
{
cout << "A(string s)" << endl;
}
void *operator new(size_t size)
{
cout << "void *operator new(size_t size)" << endl;
if(void *ptr=malloc(size))
return ptr;
else
throw bad_alloc();
}
void operator delete(void *ptr) noexcept
{
cout << "void *operator delete(void *ptr)" << endl;
free(ptr);
}
~A()
{
cout << "~A()" << endl;
}
private:
string _s;
};
int main()
{
A *pA=new A("hello world!");
delete pA;
return 0;
}
运行结果:
placement new
placement new的调用形式:
new (place_address) type
new (place_address) type (initializers)
new (place_address) type [size]
new (place_address) type [size] { braced initializer list }
placement new调用的是operator new(size_t, void *)(不允许用户重定义)版本分配内存。place_address指针不必要指向operator new分配的内存,可以指向事先申请的内存缓冲区甚至是栈上的空间。这样的话我们就可以提前申请足够的内存,不需要每次都申请和释放内存,通过显示调用析构函数而不释放内存,提高了运行时的效率。