整理下下c++ 下new 和 operator new

来源:互联网 发布:预算用什么软件 编辑:程序博客网 时间:2024/04/30 00:10

根据网上以及平常学习所得整理了下new和operator new的关系:

1.new是操作符而operator new是函数,当在c++代码中调用new,首先会调用operator new来分配内存,分配内存之后,需要调用相关累的构造函数进行初始化内存

最后返回指向内存的指针

#include <iostream>
using namespace std;

class Aa
{
public:
 Aa(){cout<<"bein to call constructions."<<endl;}
 void* operator new(size_t size)
 {
  cout<<"begin to new."<<endl;
  return ::operator new(size);
 }
};
int main()
{
 Aa* a= new Aa();
 delete a;
}

如上代码得到结果为:

begin to new.

bein to call constructions.


2.operator  new具有三种形式:

throwing (1)
void* operator new (std::size_t size) throw (std::bad_alloc);
nothrow (2)
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) throw();
placement (3)
void* operator new (std::size_t size, void* ptr) throw();

其中经常使用的是前两个,他们之间的区别仅在于是否能抛出异常,第三个new用法为placement new,主要作用为对已经分配的内存初始化,如下代码:

class Aa
{
public:
 Aa(){cout<<"bein to call constructions."<<endl;}
 void* operator new(size_t size,void * p)
 {
  cout<<"begin to new."<<endl;
  return ::operator new(size,p);
 }

~Aa(){cout<<"begin to call destruction."<<endl;}
};
int main()
{
 void* a = malloc(100);
 Aa* a1= new(a)Aa();

 a1->~Aa();
 delete a;
}

所得到的结果与上面一样

3.placement new特殊点在于在该内存需要释放的时候需要手动调用析构函数,之所以需要手动调用的原因如下:

      1.与operator new拥有三种形式外,operator delete同样拥有3种形式,并且他们是一一对应的

      2.如果看下placement new对应的delete函数实现为:

      inline void __CRTDECL operator delete(void *, void *) _THROW0()
      { // delete if placement new fails
      }

      也就是里面什么都不会做,所以对于析构的去初始化操作还是需要手动去掉用,而且绝对不可以对原有内存进行delete,该行为可能引起无法确认的问题







0 0
原创粉丝点击