OOP HomeWork
This commit is contained in:
76
oop_hw4/hw6/main.cpp
Normal file
76
oop_hw4/hw6/main.cpp
Normal file
@@ -0,0 +1,76 @@
|
||||
#include <iostream>
|
||||
#include <cstddef>
|
||||
|
||||
class A {
|
||||
private:
|
||||
int data[10]; // ģ<><C4A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڲ<EFBFBD><DAB2><EFBFBD><EFBFBD><EFBFBD>
|
||||
|
||||
// <20><>̬<EFBFBD><CCAC>Ա<EFBFBD><D4B1><EFBFBD><EFBFBD>ͳ<EFBFBD><CDB3>
|
||||
static size_t createdCount;
|
||||
static size_t destroyedCount;
|
||||
static size_t totalAllocatedBytes;
|
||||
static size_t currentUsedBytes;
|
||||
|
||||
public:
|
||||
// <20><><EFBFBD><EFBFBD> new
|
||||
void* operator new(size_t size) {
|
||||
createdCount++;
|
||||
totalAllocatedBytes += size;
|
||||
currentUsedBytes += size;
|
||||
std::cout << "[new] size = " << size << std::endl;
|
||||
return ::operator new(size);
|
||||
}
|
||||
|
||||
// <20><><EFBFBD><EFBFBD> delete
|
||||
void operator delete(void* ptr, size_t size) {
|
||||
destroyedCount++;
|
||||
currentUsedBytes -= size;
|
||||
std::cout << "[delete] size = " << size << std::endl;
|
||||
::operator delete(ptr);
|
||||
}
|
||||
|
||||
// <20><><EFBFBD><EFBFBD> new[]
|
||||
void* operator new[](size_t size) {
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD>ڿ<EFBFBD><DABF>ܺ<EFBFBD><DCBA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><F3A3ACBC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
createdCount++; // ע<>⣺<EFBFBD><E2A3BA><EFBFBD><EFBFBD>ֻͳ<D6BB><CDB3>һ<EFBFBD>Σ<EFBFBD><CEA3>ɸ<EFBFBD><C9B8><EFBFBD>ϸͳ<CFB8><CDB3>
|
||||
totalAllocatedBytes += size;
|
||||
currentUsedBytes += size;
|
||||
std::cout << "[new[]] size = " << size << std::endl;
|
||||
return ::operator new[](size);
|
||||
}
|
||||
|
||||
// <20><><EFBFBD><EFBFBD> delete[]
|
||||
void operator delete[](void* ptr, size_t size) {
|
||||
destroyedCount++; // ͬ<><CDAC>
|
||||
currentUsedBytes -= size;
|
||||
std::cout << "[delete[]] size = " << size << std::endl;
|
||||
::operator delete[](ptr);
|
||||
}
|
||||
|
||||
// ͳ<><CDB3><EFBFBD><EFBFBD>Ϣ
|
||||
static void showStats() {
|
||||
std::cout << "Created: " << createdCount << std::endl;
|
||||
std::cout << "Destroyed: " << destroyedCount << std::endl;
|
||||
std::cout << "Total allocated: " << totalAllocatedBytes << " bytes" << std::endl;
|
||||
std::cout << "Current in use: " << currentUsedBytes << " bytes" << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
// <20><>̬<EFBFBD><CCAC>Ա<EFBFBD><D4B1>ʼ<EFBFBD><CABC>
|
||||
size_t A::createdCount = 0;
|
||||
size_t A::destroyedCount = 0;
|
||||
size_t A::totalAllocatedBytes = 0;
|
||||
size_t A::currentUsedBytes = 0;
|
||||
|
||||
int main() {
|
||||
A* a1 = new A;
|
||||
A* a2 = new A;
|
||||
delete a1;
|
||||
|
||||
A* arr = new A[3];
|
||||
delete[] arr;
|
||||
|
||||
A::showStats();
|
||||
return 0;
|
||||
}
|
||||
|
Reference in New Issue
Block a user