globalnew.cpp

来自「希望我提供的代码对大家有帮助」· C++ 代码 · 共 41 行

CPP
41
字号
//: C13:GlobalNew.cpp

// From Thinking in C++, 2nd Edition

// Available at http://www.BruceEckel.com

// (c) Bruce Eckel 1999

// Copyright notice in Copyright.txt

// Overload global new/delete

#include <cstdio>

#include <cstdlib>

using namespace std;



void* operator new(size_t sz) {

  printf("operator new: %d Bytes\n", sz);

  void* m = malloc(sz);

  if(!m) puts("out of memory");

  return m;

}



void operator delete(void* m) {

  puts("operator delete");

  free(m);

}



class S {

  int i[100];

public:

  S() { puts("S::S()"); }

  ~S() { puts("S::~S()"); }

};



int main() {

  puts("creating & destroying an int");

  int* p = new int(47);

  delete p;

  puts("creating & destroying an s");

  S* s = new S;

  delete s;

  puts("creating & destroying S[3]");

  S* sa = new S[3];

  delete []sa;

} ///:~

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?