Originally I was going to write this article to detail a particular problem I had recently with placement new in C++.  A page or two of writing later I decided it would be best to start with an introduction to the "new" operator itself and the in/outs of overloading/replacing it.  The C++ new operator really functions as a 2 step process.

  1. Allocate memory - This is accomplished by calling the in scope "new" operator
  2. Construct object in the allocated memory - Essentially the "this" pointer is pointed to the front of the memory and the constructor is called. 

You can customize the new operator in your code by defined operator new at a particular scope. 

static
 inline

void
 * _cdecl
 operator
 new
(size_t cbSize)

{

... // Return cbSize bytes

}

One item a lot of people don't realize is that "new" is for most purposes a normal C++ function.  Like a normal C++ function you can add parameters.  Below is a common overload you will see in code.  It is typically referred to as placement new. 

// Placement new


static
 inline

void
 * _cdecl
 operator
 new
(

    size_t cbSize,

    void
 * pv)

{

    return
 pv;

}

The next question is how to pass the "pv" parameter?  When you want to pass additional parameters to "new" you can do so by opening up an argument paren block immediately after the new.  When attempting to bind the operator "new" in scope, the C++ compiler will match the first passed argument to the second argument of the defined new, second to third and so on. 

Student *p = new
 (NULL) Student();

This will match the second new operator I defined as NULL is compatible with void*.  This particular version of new, placement new, is valuable because it lets you customize how memory is allocated for a particular operation but still us standard C++ constructor syntax.  When you redefine operator new you are only taking care of the first step in the C++ new process; memory allocation.  The compiler will still perform step #2 on the memory returned from new.  This allows the following pattern.

    void
 *p = myAllocator.Allocate(sizeof
(Student));



http://blogs.msdn.com/b/jaredpar/archive/2007/10/16/c-new-operator-and-placement-new.aspx

    Student *p = new
 (p) Student();

The second line will bind to the placement new operator I defined above and will simply return the value of "p".  Student will then be constructed in this memory. 

Next time I'll dive into how to make the placement new operator make a custom allocation pattern easier.

http://www.cppblog.com/guojingjia2006/archive/2010/09/30/128143.html?opt=admin

今天看STL源码遇到一个问题:
 
template <class _T1, class _T2>
inline void _Construct(_T1* __p, const _T2& __value) {
  new ((void*) __p) _T1(__value);
}
 
上网搜到了一些文章,分享了:
 
原帖地址: http://www.ksarea.com/articles/20080124_cc.html
 

"placement new"? Embarrassed它 到底是什么东东呀?我也是最近几天才听说,看来对于C++我还差很远呀!placement new 是重载operator new的一个标准、全局的版本,它不能被自定义的版本代替(不像普通的operator new和operator delete能够被替换成用户自定义的版本)。

它的原型如下: 
void *operator new( size_t, void *p ) throw()  { return p; }

首先我们区分下几个容易混淆的关键词:new、operator new、placement new 
new和delete操作符我们应该都用过,它们是对中的内存进行申请和释放,而这两个都是不能被重载的。要实现不同的内存分配行为,需要重载operator new,而不是new和delete。I dont know

看如下代码: 
class MyClass {…}; 
MyClass * p=new MyClass;

这里的new实际上是执行如下3个过程:


1. 调用operator new分配内存 ;2. 调用构造函数生成类对象;3. 返回相应指针。

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非常适合那些对时间要求比较高,长时间运行不希望被打断的应用程序。

使用方法如下: 
1. 缓冲区提前分配 
可以使用堆的空间,也可以使用栈的空间,所以分配方式有如下两种: 
class MyClass {…}; 
char *buf=new char[N*sizeof(MyClass)+sizeof(int)];或者char buf[N*sizeof(MyClass)+sizeof(int)];

2. 对象的构造 
MyClass * pClass=new(buf) MyClass;

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



placement new 是重载operator new 的一个标准、全局的版本,它不能够被自定义的版本代替(不像普通版本的operator new 和 operator delete能够被替换)。

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

placement new的执行忽略了size_t参数,只返还第二个参数。其结果是允许用户把一个对象放到一个特定的地方,达到调用构造函数的效果。

和其他普通的new不同的是,它在括号里多了另外一个参数。比如:
Widget * p = new Widget; - - - - - - - - - //ordinary new 
pi = new (ptr) int; pi = new (ptr) int;     //placement new

括 号里的参数ptr是一个指针,它指向一个内存缓冲器,placement new将在这个缓冲器上分配一个对象。Placement new的返回值是这 个被构造对象的地址(比如括号中的传递参数)。placement new主要适用于:在对时间要求非常高的应用程序中,因为这些程序分配的时间是确定 的;长时间运行而不被打断的程序;以及执行一个垃圾收集器 (garbage collector)。
    new 、operator new 和 placement new 区别
new :不能被重载,其行为总是一致的。它先调用operator new分配内存,然后调用构造函数初始化那段内存。

operator new:要实现不同的内存分配行为,应该重载operator new,而不是new。

delete和operator delete类似。

placement new:只是operator new重载的一个版本。它并不分配内存,只是返回指向已经分配好的某段内存的一个指针。因此不能删除它,但需要调用对象的析构函数。
    new 操作符的执行过程
1. 调用operator new分配内存 ;
2. 调用构造函数生成类对象;
3. 返回相应指针。

operator new 就像operator+一样,是可以重载的。如果类中没有重载operator new,那么调用的就是全局的::operator new来完成堆的分 配。同理,operator new[]、operator delete、operator delete[]也是可以重载的,其实 operator new也是operator new的一个重载的版本,只是很少用而已。如果你想在已经分配的内存中创建一个对象,使用new时行不通 的。也就是说placement new允许你在一个已经分配好的内存中(栈或者堆中)构造一个新的对象。原型中void*p实际上就是指向一个已经分配 好的内存缓冲区的的首地址。
    Placement new 存在的理由
1.用Placement new 解决buffer的问题

问 题描述:用new分配的数组缓冲时,由于调用了默认构造函数,因此执行效率上不佳。若没有默认构造函数则会发生编译时错误。如果你想在预分配的内存上创建 对象,用缺省的new操作符是行不通的。要解决这个问题,你可以用placement new构造。它允许你构造一个新对象到预分配的内存上。

2.增大时空效率的问题
 
使用new操作符分配内存需要在堆中查找足够大的剩余空间,显然这个操作速度是很慢的,而且有可能出现无法分配内存的异常(空间不够)。 
placement new 就可以解决这个问题。我们构造对象都是在一个预先准备好了的内存缓冲区中进行,不需要查找内存,内存分配的时间是常数;而且不会出现在程序运行中途出现内 存不足的异常。所以,placement new非常适合那些对时间要求比较高,长时间运行不希望被打断的应用程序。
    使用步骤
在很多情况下,placement new的使用方法和其他普通的new有所不同。这里提供了它的使用步骤。

第一步  缓存提前分配
有三种方式:
1.为了保证通过placement new使用的缓存区的memory alignmen(内存队列)正确准备,使用普通的new来分配它:在堆上进行分配

class Task ;

char * buff = new [sizeof(Task)]; //分配内存

(请注意auto或者static内存并非都正确地为每一个对象类型排列,所以,你将不能以placement new使用它们。)

2.在栈上进行分配

class Task ;
char buf[N*sizeof(Task)]; //分配内存

3.还有一种方式,就是直接通过地址来使用。(必须是有意义的地址)

void* buf = reinterpret_cast<void*> (0xF00F);

第二步:对象的分配

在刚才已分配的缓存区调用placement new来构造一个对象。

Task *ptask = new (buf) Task
第三步:使用
按照普通方式使用分配的对象:

ptask->memberfunction();

ptask-> member;

//...

第四步:对象的析构

一旦你使用完这个对象,你必须调用它的析构函数来毁灭它。按照下面的方式调用析构函数:

ptask->~Task(); //调用外在的析构函数

第五步:释放

你可以反复利用缓存并给它分配一个新的对象(重复步骤2,3,4)如果你不打算再次使用这个缓存,你可以象这样释放它:

delete [] buf;

跳过任何步骤就可能导致运行时间的崩溃,内存泄露,以及其它的意想不到的情况。如果你确实需要使用placement new,请认真遵循以上的步骤。