new operator,operator new and replacement new

来源:互联网 发布:软件安全在线检测 编辑:程序博客网 时间:2024/06/05 07:01

 new operator:指在C++里通常用到的关键字
operator new:它是一个操作符,并且可被重载
关系:
operator new can be called explicitly as a regular function, but in C++, new is an operator with a very specific behavior: An expression with the new operator, first calls function operator new (i.e., this function) with the size of its type specifier as first argument, and if this is successful, it then automatically initializes or constructs the object (if needed). Finally, the expression evaluates as a pointer to the appropriate type.

B* b = new B;
我们知道这里分为三步:1.分配内存,2.调用A()构造对象,3. 返回分配指针。事实上,分配内存这一操作就是由operator new(size_t)来完成的,如果类A重载了operator new,那么将调用A::operator new(size_t ),否则调用全局::operator new(size_t ),后者由C++默认提供。因此前面的步骤也就是:
调用operator new (sizeof(A))
调用A:A()
返回指针
replacement new:是在申请的内存上调用类的构造函数。
例子如:
new (T*) T(value)

0 0
原创粉丝点击