用malloc和free
#include <stdio.h> /* printf() */ #include <stdlib.h> #include <unistd.h> /* for write() */ extern "C" void* c_new(size_t size) { void *p = malloc(size); if (! p) { (void)!write(2, "ERROR: run out of memory/n", 25); abort(); } return p; } extern "C" void c_delete(void* p) { if (p) free(p); } void* operator new (size_t size) __attribute__((alias("c_new"))); void* operator new[] (size_t size) __attribute__((alias("c_new"))); void operator delete (void *p) __attribute__((alias("c_delete"))); void operator delete[] (void *p) __attribute__((alias("c_delete"))); int main() { const int n = 10; int* a = new int[n]; for (int j = 0; j < n; ++j) { if (j == 0) { a[j] = 1; } else if (j == 1) { a[j] = 2; } else { a[j] = a[j-1] + a[j-2]; } } for (int j = 0; j < n; ++j) { printf("%d,", a[j]); } delete a; return 0; }
编译
$ g++ -o fake_cpp.o -c fake_cpp.c -fno-rtti -fno-exceptions
执行
$ gcc -o fake_cpp fake_cpp.o