matrix
析构函数释放规律
局部变量储存在栈区域
所以释放的时候采用“后创建 先释放”的模式
并且在函数内在创建一个栈,例如花括号,函数递归,会先释放内部栈元素,再释放外部栈元素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
using namespace std;
class MyClass {
private:
int id;
static int count; // 静态成员变量
public:
MyClass(int id){
this->id=id;
count++;
cout << "Constructor: Object " << this->id << " created. Total objects: " << count << endl;
}
~MyClass() {
count--;
cout << "Destructor: Object " << this->id << " destroyed. Total objects: " << count << endl;
}
void showId() const {
cout << "Object ID: " << this->id << endl;
}
static int getCount() { // 静态成员函数
return count;
}
};
int MyClass::count = 0; // 初始化静态成员变量
int main() {
MyClass obj1(1);
{
MyClass obj2(2);
obj2.showId();
}
cout << "Total objects after block: " << MyClass::getCount() << endl;
return 0;
}
输出:
Constructor: Object 1 created. Total objects: 1
Constructor: Object 2 created. Total objects: 2
Object ID: 2
Destructor: Object 2 destroyed. Total objects: 1
Total objects after block: 1
Destructor: Object 1 destroyed. Total objects: 0
malloc不调用构造函数
malloc不调用构造函数,free不调用析构函数
它们两个和new与delete比起来就只是分配了内存和释放了内存而已
1 |
|
思考:
new能否调用有参构造函数?
回复:
单个对象的new可以使用,数组无法使用
解决办法:
创建指针数组,对每个指针new
1 | Test* arr[3]; |
注意,这样得到的就是一个指针数组,$arr[0]$是指针,而非Test对象
new分配内存失败
1 |
|
如果有new头文件(储存异常宏)
会直接终止程序,抛出std::bad_alloc异常没有好像也没关系
但是如果把new加上修饰符,内存分配失败的时候就会返回空指针而不是抛出异常1
2
3
4int* p = new(std::nothrow) int[1000000]; // 若分配失败,p 为 nullptr,而不是抛出异常
if (!p) {
std::cout << "内存分配失败" << std::endl;
}
default和delete使用限制
default可以在外部使用,也可以在内部使用
delete只能在第一次声明时写出,在类外部写出是非法的
delete报错与未定义
使用delete释放非指针变量时编译会报错
多次释放同一个指针地址会导致未定义行为(和数组越界,对new出的数组使用delete p差别不大)
拷贝构造函数/拷贝运算符/拷贝优化
1 |
|