基础14 C++申请内存的各种方法
一、内存的手动申请与释放
🥦 malloc/free
void *p1 = malloc(sizeof(Test) * 10);
free(p1);
- 这2个是c语言中的函数,malloc单纯的只是为了申请一块固定大小的内存,free只是单纯的为了将内存释放掉
- free在内存释放的时候,并没有传入释放内存的大小,所以对于malloc来说它每次执行所有申请的堆内存一般会更大。至少要存一些申请了多少
🥝 new/delete
new 和 delete 是C++函数,所以内部要调用构造与析构
Test* p2=new Test();
// 等价
void* mem=operator new(sizeof(Test));
Test* p2=(Test*)mem;
p2->Test::Test();
delete p2;
// 等价
p2->~Test();
operator delete(p2);
🥑 placement new
placement new 需要传入一块分配好内存的指针,所以其本身不会额外申请内存空间
Test* p3=new(p1)Test();
// 等价
void* mem=operator new (sizeof(Test), p1);
Test*p3 = (Test*)mem;
p3->Test::Test();
二、完全掌控内存的申请与释放
#include <iostream>
#include <vector>
#include <string>
class Test
{
public:
Test() { std::cout << "Test() addr is: " << this << std::endl; }
Test(int a) : _a(a)
{
std::cout << "Test(int a) addr is: " << this << std::endl;
}
Test(int a, int b) { std::cout << "Test(int a, int b) addr is: " << this << std::endl; }
~Test() { std::cout << "~Test() addr is: " << this << std::endl; }
void *operator new(size_t size)
{
std::cout << "operator new(size_t size)" << std::endl;
return malloc(size);
}
void *operator new(size_t size, void *buf)
{
std::cout << "operator new(size_t size, void* buf)" << std::endl;
return buf;
}
void operator delete(void *ptr, size_t size)
{
std::cout << "operator delete(void* ptr, size_t size)" << std::endl;
free(ptr);
}
void operator delete(void *ptr, void *buf)
{
std::cout << "operator delete(void* ptr, void* buf)" << std::endl;
free(ptr);
}
private:
int _a;
};
int main()
{
// void *p1 = malloc(sizeof(Test) * 10);
// free(p1);
// int *p2 = (int *)malloc(sizeof(Test) * 10);
// free((++p2)); // 会崩溃,因为p2指向别处,他就不知道应该释放多少堆内存啦
Test *p3 = new Test();
delete p3;
std::cout<<"---------------------------"<<std::endl;
void *buf = malloc(sizeof(Test));
Test *p4 = new (buf) Test(500);
delete p4; // 会调用operator delete(void* ptr)
return 0;
}
operator new(size_t size)
Test() addr is: 0x555555769680
~Test() addr is: 0x555555769680
operator delete(void* ptr, size_t size)
---------------------------
operator new(size_t size, void* buf)
Test(int a) addr is: 0x555555769680
~Test() addr is: 0x555555769680
operator delete(void* ptr, size_t size)