bruce@bruce-localhost ~ $ cat test.cc
#include <iostream>
#include <stdlib.h>
class Test
{
public:
static void allocate(size_t n)
{
ptr = (int *)::malloc(n);
*ptr = 4;
}
~Test()
{
std::cout<< "hello world" << std::endl;
free(ptr);
}
private:
static int * ptr;
};
int* Test::ptr = nullptr;
int main()
{
Test::allocate(sizeof(int));
return 0;
}
有没有任何办法释放掉malloc
分配的内存?
既然你专门写了一个
allocate
来分配内存,为什么不写一个free
来释放内存呢如果你想在析构函数中释放,也不是不可能,但是注意不要重复释放,而且,如果没有对象,就不会产生析构。