码迷,mamicode.com
首页 > 编程语言 > 详细

C++中的::operator new, ::operator delete

时间:2015-05-19 12:12:42      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

一般在使用new  和 delete的时候,做了两件事情,一是空间的配置( new 是分配,delete是回收),而是调用对象的析构函数

 但是也有办法将这两个过程分开

 那就是显式的调用::operator new, ::operator delete,它们只进行空间配置,并不调用对象的析构函数

具体的可以参看下面这个例子:

// operator new[] example
#include <iostream>     // std::cout
#include <new>          // ::operator new[]

struct MyClass {
  int data;
  MyClass() {std::cout << ‘*‘;}  // print an asterisk for each construction
};

int main () {
  std::cout << "constructions (1): ";
  // allocates and constructs five objects:
  MyClass * p1 = new MyClass[5];
  std::cout << ‘\n‘;

  std::cout << "constructions (2): ";
  // allocates and constructs five objects (nothrow):
  MyClass * p2 = new (std::nothrow) MyClass[5];
  std::cout << ‘\n‘;

  std::cout << "constructions (3): ";
  // allocates storage for five objects, but does not construct them:
  MyClass * p3 = static_cast<MyClass*> (::operator new (sizeof(MyClass[5])));
  std::cout << ‘\n‘;

  std::cout << "constructions (4): ";
  // constructs five objects at p3, but does not allocate:
  new (p3) MyClass[5];
  std::cout << ‘\n‘;

  delete[] p3;
  delete[] p2;
  delete[] p1;

  return 0;
}

关于operator delete和operator new  ,可以参看这里的原型定义:

http://en.cppreference.com/w/cpp/memory/new/operator_delete

http://en.cppreference.com/w/cpp/memory/new/operator_new

可以看到,都是void*型的指针,跟C语言里面的malloc  free机制差不多了。

C++中的::operator new, ::operator delete

标签:

原文地址:http://www.cnblogs.com/hustxujinkang/p/4513796.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!