new、operator new、placement new

首先咱們區分下幾個容易混淆的關鍵詞:html

   

new、operator new、placement new

newdelete操做符咱們應該都用過,它們是對堆中的內存進行申請和釋放,而這兩個都是不能被重載的。要實現不一樣的內存分配行爲,須要重載operator new,而不是newdeleteios

operator new
(1)  只分配所要求的空間,不調用相關對象的構造函數。當沒法知足所要求分配的空間時,則
       ->若是有new_handler,則調用new_handler,不然
       ->若是沒要求不拋出異常(以nothrow參數表達),則執行bad_alloc異常,不然
       ->返回0
(2)  能夠被重載
    可是不能在全局對原型爲void operator new(size_t size)這個原型進行重載,
    通常只能在類中進行重載。若是類中沒有重載operator new,
    那麼調用的就是全局的::operator new來完成堆的分配。
    同理,operator new[]、operator delete、operator delete[]也是能夠重載的。
(3) 重載時,返回類型必須聲明爲void* (4) 重載時,第一個參數類型必須爲表達要求分配空間的大小(字節),類型爲size_t (5) 重載時,能夠帶其它參數
new(也稱做new operator)

1) 調用operator new分配足夠的空間,並調用相關對象的構造函數 (2) 不能夠被重載
 
 
placement new 是重載operator new的一個標準、全局的版本。它不能被自定義的版本代替(不像普通的operator new和operator delete可以被替換成用戶自定義的版本)。它的原型以下:
 

void *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
{ 數組

  // try to allocate size bytes
  void *p;
  while ((p = malloc(size)) == 0)
  if (_callnewh(size) == 0)
  { 函數

    // report no memory
    static const std::bad_alloc nomem;
     _RAISE(nomem);
      }this

    return (p);spa

}指針

  placement new,只是operator new的一個重載的版本,只是咱們不多用到它。若是你想在已經分配的內存中建立一個對象,使用new時行不通的。也就是說placement new容許你在一個已經分配好的內存中(棧或者堆中)構造一個新的對象。原型中void*p實際上就是指向一個已經分配好的內存緩衝區的的首地址。code

   咱們知道使用new操做符分配內存須要在堆中查找足夠大的剩餘空間,這個操做速度是很慢的,並且有可能出現沒法分配內存的異常(空間不夠)placement new就能夠解決這個問題。咱們構造對象都是在一個預先準備好了的內存緩衝區中進行,不須要查找內存,內存分配的時間是常數。並且不會出如今程序運行中途出現內存不足的異常。因此,placement new很是適合那些對時間要求比較高,長時間運行不但願被打斷的應用程序placement new使用方法以下:htm

1)分配內存
  堆上:
      char* buff = new char[ sizeof(Foo) ];
   memset( buff, 0, sizeof(Foo));
  棧上:
char buf[ sizeof(Foo) ]={0};
2)構建對象
    Foo* pfoo = new (buff)Foo;
3)使用對象
    pfoo->print();
    pfoo->set_f(1.0f);
    pfoo->get_f();
 
4)析構對象,顯式的調用類的析構函數。
    pfoo->~Foo();
5)銷燬內存
    delete [] buff;

placement new的好處:
1)在已分配好的內存上進行對象的構建,構建速度快。
2)已分配好的內存能夠反覆利用,有效的避免內存碎片問題。  對象

Placement new的標準用法:

#include <iostream>
using namespace std;

class Foo
{
  char cc;
  float f;

public:
  void print() { std::cout << "ADDR: " << this << std::endl; }
  void set_f( float _f ) { std::cout << "set f val : " << _f << std::endl; f = _f; }
  void get_f() { std::cout << "get f val : " << f << std::endl; }
  ~Foo(){ cout <<"~Foo()"<<endl; }
};
int main()
{
     char* buff = new char[ sizeof(Foo) ];
     memset( buff, 0, sizeof(Foo) );

   Foo *pfoo = new (buff)Foo;

   pfoo->print();
   pfoo->set_f( 1.0f );
   pfoo->get_f();

     pfoo->~Foo();

   delete [] buff;
     return 0;
}

 

placement new還能夠解決的一個問題是創建帶參數的構造函數對象數組

#include <iostream>
using namespace std;
class CPong
{
public:
     CPong( int m ) : v(m) { std::cout << "CPong ctor." << std::endl; }
		
		 private:
		    int v;
	 };

int main()
{
	char* pong = new char[ sizeof(CPong) * 10 ];
	CPong* pp = (CPong*)pong;

	for ( int i=0; i<10; ++i )
	{
		new (pp+i)CPong(i);
	}

	for ( int j=0; j<10; ++j )
	{
		pp[j].~CPong();
	}

	delete [] pong;
	return 0;
}

  

注意:

      在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

     

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中。第1、第二個版本C++默認在每一個編譯單元中聲明,不須要#include <new>頭文件。第1、第二個版本能夠被用戶更換和重載,定義本身的版本,第三種placement new不可重載。

// operator new example
#include <iostream>
#include <new>
using namespace std;
 
struct myclass {myclass() {cout <<"myclass constructed\n";}};
 
int main () {
 
   int * p1 = new int;
// same as:
// int * p1 = (int*) operator new (sizeof(int));
 
   int * p2 = new (nothrow) int;
// same as:
// int * p2 = (int*) operator new (sizeof(int),nothrow);
 
   myclass * p3 = (myclass*) operator new (sizeof(myclass));
// (!) not the same as:
// myclass * p3 = new myclass;
// (constructor not called by function call, even for non-POD types)
 
   new (p3) myclass;   // calls constructor
// same as:
// operator new (sizeof(myclass),p3)
 
   return 0;
}

  重載operator new  

class Base {
public:
  Base() { }
 
  void *operator new( size_t size, string str ) {
    cout << "Logging an allocation of " << size << " bytes for new object'" << str << "'" << endl;
    return malloc( size );
  }
 
  int var;
  double var2;
};
 
...
 
Base* b = new ("Base instance 1") Base;

  new operator的四種用法

pointer = new type;
pointer = new type( initializer );
pointer = new type[size];
pointer = new( arg-list ) type...    //4th vision
 
Foo *foo; 
foo = new(nothrow) Foo();            //use the 4th vision
assert( foo );
其中,nothrow爲 C++預約義的std::nothrow_t類型全局常量。

    operator new能夠被重載,它的三個版本本質上是函數,它們只分配空間,不調用構造函數。而new、delete(也叫作new operator、delete operator)不可被重載,它們是運算符,分配空間,而且調用構造函數。

相關文章
相關標籤/搜索