new operator和operator new的区别
(2016-05-11 13:55:50)| 分类: C/CPP语法 |
replacement new:
是new的一种重载形式,也是函数,函数原型 void*
operator new (std::size_t size, void* ptr) throw();
三者的区别:
1.operator new()
会在堆中开辟一块size_t大小的连续空间,并返回指向该内存空间首地址的指针。replacement new
不会开辟新的空间,直接返回传入的空间首地址。单独使用operator new
只会开辟内存空间,并不会调用构造函数。
2.new operator会首先调用operator new
这个函数,获得一片连续的内存空间,然后调用类的构造函数,并返回指向类的指针。
3.replament new 是 operator new
的一种重载形式,使用new(*ptr) A 就会调用 replacement
new的重载形式,然后调用类的构造函数。实现在ptr所指的连续空间内初始化一个A的实例。
4.使用replacement
new时不能使用delete(会报错pointer being freed was not
allocated),必须显示调用析构函数。
C++11的新特性allocator也能实现开辟内存和调用构造函数的分离。
代码如下:
allocator alloc;
auto const d =
alloc.allocate(1);//分配一个A类大小的未初始化的内存空间。
alloc.construct(d);//调用A的构造函数
alloc.destroy(d);//调用析构函数,可以用d->~A()代替
alloc.deallocate(d,1);//释放以d开头,1个A类长度的空间
测试代码:
#include
#include
using namespace std;
class A
{
public:
A(){cout<<"call
constructor"<<endl;}
~A(){cout<<"call
destructor"<<endl;}
};
int main(int argc, char const
*argv[])
{
A *a = new A;
delete a;
char buf[128];
//A *b = new(buf) A;//replacement
new
new(buf) A;
//operator
new(sizeof(A),buf);
//delete b;
((A*)buf)->~A();
//A *c = (A*)::operator
new(sizeof(A));
//new(c) A();//replacement
new
char c[128];
new(cc) A;
cc->~A();
//::operator delete(cc);
//delete c;
allocator alloc;
auto const d =
alloc.allocate(1);
alloc.construct(d);
alloc.destroy(d);
alloc.deallocate(d,1);
//allocator alloc;
auto const e =
alloc.allocate(1);
alloc.construct(e);
//alloc.destroy(e);
e->~A();
alloc.deallocate(e,1);
return 0;
}
显示结果:
call constructor
call destructor
call constructor
call destructor
call constructor
call destructor
call constructor
call destructor
call constructor
call destructor

加载中…