C++ new 和Placement New 以及nothrow new

 

new有三种使用方式:plain new,nothrow new和placement new。

(1)plain new顾名思义就是普通的new,就是我们惯常使用的new。在C++中是这样定义的:

    void* operator new(std::size_t) throw(std::bad_alloc);

    void operator delete(void *) throw();

提示:plain new在分配失败的情况下,抛出异常std::bad_alloc而不是返回NULL,因此通过判断返回值是否为NULL是徒劳的。

(2)nothrow new是不抛出异常的运算符new的形式。nothrow new在失败时,返回NULL。定义如下:

    void * operator new(std::size_t,const std::nothrow_t&) throw();

    void operator delete(void*) throw();

(3)placement new意即“放置”,这种new允许在一块已经分配成功的内存上重新构造对象或对象数组。placement new不用担心内存分配失败,因为它根本不分配内存,它做的唯一一件事情就是调用对象的构造函数。定义如下:

    void* operator new(size_t,void*);

    void operator delete(void*,void*);

提示1:palcement new的主要用途就是反复使用一块较大的动态分配的内存来构造不同类型的对象或者他们的数组。

提示2:placement new构造起来的对象或其数组,要显示的调用他们的析构函数来销毁,千万不要使用delete。

char* p = new(nothrow) char[100];

long *q1 = new(p) long(100);

int *q2 = new(p) int[100/sizeof(int)];

char* p = new(nothrow) char[100];

long *q1 = new(p) long(100);

int *q2 = new(p) int[100/sizeof(int)];

这三句的意思是先用nothrow new申请char[100]空间,再在这片空间上申请一个long类型的空间存放100,然后是int型的数组

 

更多阅读链接

http://www.scs.stanford.edu/~dm/home/papers/c++-new.html

http://eli.thegreenplace.net/2011/02/17/the-many-faces-of-operator-new-in-c/  !!!!!!!

http://en.wikipedia.org/wiki/Placement_syntax

http://blog.csdn.net/huyiyang2010/article/details/5984987

http://www.gotw.ca/publications/mill15.htm 

http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=170

 

 

posted on 2011-12-14 23:08  阿笨猫  阅读(2687)  评论(0编辑  收藏  举报