标签:
1 class A 2 { 3 public: 4 A() 5 { 6 std::cout<<"call A constructor"<<std::endl; 7 } 8 9 ~A() 10 { 11 std::cout<<"call A destructor"<<std::endl; 12 } 13 14 void* operator new(size_t size) 15 { 16 std::cout<<"call A::operator new[] size:"<<size<<std::endl; 17 return malloc(size); 18 } 19 void operator delete[](void* p) 20 { 21 std::cout<<"call A::operator delete[]"<<std::endl; 22 free(p); 23 } 24 void operator delete(void* p) 25 { 26 free(p); 27 } 28 };#include <iostream> #include "A.h" 29 30 void* operator new[](size_t size) 31 { 32 std::cout<<"call global new[] size: "<<size<<std::endl; 33 return malloc(size); 34 } 35 36 void operator delete[](void* p) 37 { 38 std::cout<<"call global delete[] "<<std::endl; 39 } 40 int _tmain(int argc, _TCHAR* argv[]) 41 { 42 std::cout<<"sizeof A "<<sizeof(A)<<std::endl; 43 A* p1 = new A[3]; 44 delete []p1; 45 46 system("pause"); 47 return 0; 48 }
call global new[] size:7
call global new[] size:3
1 size_t mask = sizeof(void*) - 1; 2 size_t p2 = reinterpret_cast<size_t>(p1 - 1); 3 p2 = p2 & ~mask; 4 std::cout << *reinterpret_cast<int*>(p2) << std::endl;
c++为什么定义了析构函数的类的operator new[]传入的参数会多4字节?
标签:
原文地址:http://www.cnblogs.com/wubugui/p/4247726.html