编写 C++ 析构函数
Writing C++ Destructor
如果我定义自定义析构函数,是否必须手动删除每个变量?
malloc
分配的内存应该在析构函数中free
d。指向malloc
和int
分配的内存的指针怎么样?
a.h:
#ifndef A_H
#define A_H
#include <stdlib.h>
#include <iostream>
#include <stdint.h>
using namespace std;
class A{
public:
uint32_t x;
uint32_t* ar_y;
A(void);
~A(void);
};
#endif
a.cpp:
#include "a.h"
A::A(void){
x = 0;
ar_y = (uint32_t*)(malloc(4));
}
A::~A(void){
// free the memory allocated by malloc
free(ar_y);
//Is it ok to do nothing for int* y and int x?
}
test.cpp:
#include "a.h"
int f(void){
A objA;
//cout << objA.x << endl;
//Upon exiting the function
//destructor of A is called.
}
int main(void){
uint32_t i;
// see if memory usage go crazy.
for (i = 0; i < 10000000000; i++) f();
}
测试结果:
内存占用并没有疯涨
您不需要为 x
做任何事情。您需要注意释放 ar_y
.
指向的内存
有关为 class 中的成员变量分配内存时需要执行的操作的详细信息,请参阅 What is The Rule of Three?。
由于您在 C++ 领域,更喜欢使用 new
和 delete
运算符而不是使用 malloc
和 free
.
如果我定义自定义析构函数,是否必须手动删除每个变量?
malloc
分配的内存应该在析构函数中free
d。指向malloc
和int
分配的内存的指针怎么样?
a.h:
#ifndef A_H
#define A_H
#include <stdlib.h>
#include <iostream>
#include <stdint.h>
using namespace std;
class A{
public:
uint32_t x;
uint32_t* ar_y;
A(void);
~A(void);
};
#endif
a.cpp:
#include "a.h"
A::A(void){
x = 0;
ar_y = (uint32_t*)(malloc(4));
}
A::~A(void){
// free the memory allocated by malloc
free(ar_y);
//Is it ok to do nothing for int* y and int x?
}
test.cpp:
#include "a.h"
int f(void){
A objA;
//cout << objA.x << endl;
//Upon exiting the function
//destructor of A is called.
}
int main(void){
uint32_t i;
// see if memory usage go crazy.
for (i = 0; i < 10000000000; i++) f();
}
测试结果:
内存占用并没有疯涨
您不需要为 x
做任何事情。您需要注意释放 ar_y
.
有关为 class 中的成员变量分配内存时需要执行的操作的详细信息,请参阅 What is The Rule of Three?。
由于您在 C++ 领域,更喜欢使用 new
和 delete
运算符而不是使用 malloc
和 free
.