Placement new、operator new、new operator 完全释疑

全文 转自:http://www.cnblogs.com/younes/archive/2010/04/26/1721528.html,请尊重作者版权。

Placement new、operator new、new operator 完全释疑

首先我们区分下几个容易混淆的关键词:

new(也称作new operator)、operator new、placement new。看如下代码:

   1: class MyClass {...}; 
   2: MyClass *p = new MyClass; 

这里的new是上述三个关键字中的第一个,成为new操作符。实际上它执行如下3个过程:

1. 调用operator new分配内存

2. 调用构造函数生成类对象

3. 返回相应指针

placement new 是重载operator new的一个标准、全局的版本。它不能被自定义的版本代替(不像普通的operator new和operator delete能够被替换成用户自定义的版本)。它的原型如下:

1void *operator new( size_t, void *p ) throw() { return p; }

new和delete操作符我们应该都用过,它们是对堆中的内存进行申请和释放,而这两个都是不能被重载的。要实现不同的内存分配行为,需要重载operator new和operator delete,而不是new和delete。

operator new就像operator+一样,是可以重载的。但是不能在全局对原型为void operator new(size_t size)这个原型进行重载,一般只能在类中进行重载。如果类中没有重载operator new,那么调用的就是全局的::operator new来完成堆的分配。同理,operator new[]、operator delete、operator delete[]也是可以重载的。

至于placement new,只是operator new的一个重载的版本,只是我们很少用到它。如果你想在已经分配的内存中创建一个对象,使用new时行不通的。也就是说placement new允许你在一个已经分配好的内存中(栈或者堆中)构造一个新的对象。原型中void*p实际上就是指向一个已经分配好的内存缓冲区的的首地址。

我们知道使用new操作符分配内存需要在堆中查找足够大的剩余空间,这个操作速度是很慢的,而且有可能出现无法分配内存的异常(空间不够)。placement new就可以解决这个问题。我们构造对象都是在一个预先准备好了的内存缓冲区中进行,不需要查找内存,内存分配的时间是常数。而且不会出现在程序运行中途出现内存不足的异常。所以,placement new非常适合那些对时间要求比较高,长时间运行不希望被打断的应用程序。 placement new使用方法如下:

1. 缓冲区提前分配,可以使用堆的空间,也可以使用栈的空间。所以分配方式有如下两种:

1class MyClass {…};
2char *buf=new char[N*sizeof(MyClass)+sizeof(int)];
3char buf[N*sizeof(MyClass)+sizeof(int)];

2. 对象的构造

1MyClass * pClass=new(buf) MyClass; //使用placement new

3. 对象的销毁
一旦这个对象使用完毕,你必须显式的调用类的析构函数进行销毁对象。但此时内存空间不会被释放,以便其他的对象的构造。

1pClass->~MyClass();

4. 内存的释放
如果缓冲区在堆中,那么调用delete[] buf 进行内存的释放。如果在栈中,那么在其作用域内有效,跳出作用域,内存自动释放。

注意:

在C++标准中,对于placement operator new []有如下的说明: placement operator new[] needs implementation-defined amount of additional storage to save a size of array。所以我们必须申请比原始对象大小多出sizeof(int)个字节来存放对象的个数,或者说数组的大小。
使用方法第二步中的new才是使用placement new,其实是没有申请内存的,只是调用了构造函数。返回一个指向已经分配好的内存的一个指针,所以对象销毁的时候不需要调用delete释放空间,但必须调用析构函数销毁对象。

参考自:http://www.ksarea.com/articles/20080124_cc.html

以上为网友整理的资料。下面为一个C++权威参考资料:

operator new分为三种形式(前2种不调用构造函数,这点区别于new operator):

   1: void* operator new (std::size_t size) throw (std::bad_alloc);
   2: void* operator new (std::size_t size, const std::nothrow_t& nothrow_constant) throw();
   3: void* operator new (std::size_t size, void* ptr) throw();

第一种分配size个字节的存储空间,并进行对象类型进行内存对齐。如果成功,返回一个非空的指针指向首地址。失败抛出bad_alloc异常。

第二种在分配失败时不抛出异常,它返回一个NULL指针。

第三种是placement new版本。它不分配内存,调用合适的构造函数在ptr所指的地方构造一个对象,之后返回实参指针ptr。

三种版本的operator new 定义在全局命名空间,不在std中。第一、第二个版本C++默认在每个编译单元中声明,不需要#include <new>头文件。第一、第二个版本可以被用户更换和重载,定义自己的版本,第三种placement new不可重载。

例子:

01// operator new example
02#include <iostream>
03#include <new>
04using namespace std;
05
06struct myclass {myclass() {cout <<"myclass constructed\n";}};
07
08int main () {
09
10int * p1 = new int;
11// same as:
12// int * p1 = (int*) operator new (sizeof(int));
13
14int * p2 = new (nothrow) int;
15// same as:
16// int * p2 = (int*) operator new (sizeof(int),nothrow);
17
18myclass * p3 = (myclass*) operator new (sizeof(myclass));
19// (!) not the same as:
20// myclass * p3 = new myclass;
21// (constructor not called by function call, even for non-POD types)
22
23new (p3) myclass; // calls constructor
24// same as:
25// operator new (sizeof(myclass),p3)
26
27return 0;
28}

输出:myclass constructed

重载operator new

01class Base {
02public:
03Base() { }
04 
05void *operator new( size_t size, string str ) {
06cout << "Logging an allocation of " << size << " bytes for new object'" << str << "'" << endl;
07return malloc( size );
08}
09 
10int var;
11double var2;
12};
13 
14...
15 
16Base* b = new ("Base instance 1") Base;

输出: Logging an allocation of 12 bytes for new object 'Base instance 1'

new operator的四种用法

1pointer = new type;
2pointer = new type( initializer );
3pointer = new type[size];
4pointer = new( arg-list ) type... //4th vision
5 
6Foo *foo;
7foo = new(nothrow) Foo(); //use the 4th vision
8assert( foo );

其中,nothrow为 C++预定义的std::nothrow_t类型全局常量。

我的理解

operator new可以被重载,它的三个版本本质上是函数,它们只分配空间,不调用构造函数。而new、delete(也叫做new operator、delete operator)不可被重载,它们是运算符,分配空间,并且调用构造函数。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值