new operator, operator new, plac

2017-06-07  本文已影响67人  hellowenqi

本文参考地址 http://www.cnblogs.com/luxiaoxun/archive/2012/08/10/2631812.html

new operator

就是new 操作符:

operator new

是函数:

例子:

#include <iostream>
#include <string>
using namespace std;

class X{
public:
  X(){
    cout<<"constructor"<<endl;
  }
  
  void* operator new(size_t size, string str){
    cout<< "operator new " << size <<  "  " <<  str << endl;
    return ::operator new(size);
  }   
  void operator delete(void* pointer){
     cout << "operator delete" <<endl;
     ::operator delete(pointer);
  }

  ~X(){
    cout<<"destructor"<<endl;
  }
};

int main(){
  X *x = new ("str") X;
  delete x;
  return 1;
}
placement new

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

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

placement new 的执行忽略了size_t参数,只返还第二个参数。其结果是允许用户把一个对象放到一个特定的地方,达到调用构造函数的效果。和其他普通的new不同的是,它在括号里多了另外一个参数。

palcement new 存在理由

placement 使用需要五步

void* buf = reinterpret_cast<void*> (0xF00F);
Task *ptask = new (buf) Task
ptask->memberfunction();
ptask->member;
ptask->~Task(); //调用外在的析构函数

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

delete [] buf;

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

#include <iostream>
using namespace std;

class X
{
public:
    X() { cout<<"constructor of X"<<endl; }
    ~X() { cout<<"destructor of X"<<endl;}

    void SetNum(int n)
    {
        num = n;
    }

    int GetNum()
    {
        return num;
    }

private:
    int num;
};

int main()
{
    char* buf = new char[sizeof(X)];
    X *px = new(buf) X;
    px->SetNum(10);
    cout<<px->GetNum()<<endl;
    px->~X();
    delete []buf;

    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读