-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_analysis.cpp
More file actions
59 lines (50 loc) · 1.94 KB
/
Copy pathmemory_analysis.cpp
File metadata and controls
59 lines (50 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include "include/Complexe.h"
using namespace std;
// 用指针的版本(仅用于对比)
class ComplexeWithPointers {
private:
double* R;
double* I;
public:
ComplexeWithPointers(double r = 0, double i = 0) {
R = new double(r);
I = new double(i);
}
~ComplexeWithPointers() {
delete R;
delete I;
}
// 需要拷贝构造函数和赋值运算符...
ComplexeWithPointers(const ComplexeWithPointers& other) {
R = new double(*other.R);
I = new double(*other.I);
}
ComplexeWithPointers& operator=(const ComplexeWithPointers& other) {
if (this != &other) {
delete R;
delete I;
R = new double(*other.R);
I = new double(*other.I);
}
return *this;
}
};
int main() {
cout << "=== 内存占用分析 ===" << endl;
cout << "sizeof(double): " << sizeof(double) << " bytes" << endl;
cout << "sizeof(double*): " << sizeof(double*) << " bytes" << endl;
cout << "sizeof(Complexe): " << sizeof(Complexe) << " bytes" << endl;
cout << "sizeof(ComplexeWithPointers): " << sizeof(ComplexeWithPointers) << " bytes" << endl;
cout << "\n=== 实际内存使用分析 ===" << endl;
cout << "当前实现 (两个double成员):" << endl;
cout << " - 对象本身: " << sizeof(Complexe) << " bytes" << endl;
cout << " - 堆内存: 0 bytes" << endl;
cout << " - 总计: " << sizeof(Complexe) << " bytes" << endl;
cout << "\n指针版本:" << endl;
cout << " - 对象本身: " << sizeof(ComplexeWithPointers) << " bytes (两个指针)" << endl;
cout << " - 堆内存: " << 2 * sizeof(double) << " bytes (两个double)" << endl;
cout << " - 内存管理开销: ~16-32 bytes (malloc头部信息等)" << endl;
cout << " - 总计: 约 " << sizeof(ComplexeWithPointers) + 2 * sizeof(double) + 24 << " bytes" << endl;
return 0;
}