我们先来看下面的一段代码和相关问题:
#include <iostream>
using namespace std;
int main()
{
//栈
const int a = 0;
int b = 0;
cout << &a << endl;
cout << &b << endl;
const char* p = "11111111";
cout << (void*)p << endl;
return 0;
}
说明:
void Test ()
{
// 1.malloc/calloc/realloc的区别是什么?
int* p2 = (int*)calloc(4, sizeof(int));
int* p3 = (int*)realloc(p2, sizeof(int) * 10);
// 这里需要free(p2)吗?
free(p3);
}
C语言内存管理方式在C++中可以继续使用,但有些地方就无能为力,而且使用起来比较麻烦,因此C++又提出了自己的内存管理方式:通过 new 和 delete 操作符进行动态内存管理。
int main()
{
//内置类型
//除了用法方便,c malloc没什么区别
/*int* p1 = new int;
int* p2 = new int[10];*/
//默认不初始化,但是可以初始化
int* p1 = new int(0);
int* p2 = new int[10]{ 1, 2, 3, 4 };
delete p1;
delete[] p2;
return 0;
}
注意: 申请和释放单个元素的空间,使用 new 和 delete 操作符;申请和释放连续的空间,使用 new[] 和 delete[]。
#include <iostream>
using namespace std;
class A
{
public:
A(int a = 0)
:_a(a)
{
cout << "A(int a)" << endl;
}
A(int a1, int a2)
{
cout << "A(int a1, int a2)" << endl;
}
A(const A& aa)
:_a(aa._a)
{
cout << "A(const A& aa)" << endl;
}
A& operator=(const A& aa)
{
cout << "A& operator=(const A& aa)" << endl;
if (this != &aa)
{
_a = aa._a;
}
return *this;
}
~A()
{
cout << "~A()" << endl;
}
private:
int _a;
};
int main()
{
//自定义类型,new才能调用构造初始化,malloc不再适用
A* p1 = (A*)malloc(sizeof(A));
//p1->_a = 0;//err
free(p1);
//开空间/释放空间,还会调用构造和析构
A* p2 = new A;
A* p3 = new A(2);
delete p2;
delete p3;
cout << endl;
//A* p4 = new A[10];
//A aa1(1);
//A aa2(2);
//A aa3(3);
//A* p4 = new A[10]{ aa1, aa2, aa3 };
A* p4 = new A[10]{ 1, 2, 3, 4, 5, {6,7} };
delete[] p4;
return 0;
}
注意: 在申请自定义类型的空间时,new会调用构造函数,delete会调用析构函数,而 malloc 与 free不会。
new 和 delete 是用户进行动态内存申请和释放的操作符,operator new 和 operator delete 是系统提供的全局函数,new 在底层调用 operator new 全局函数来申请空间,delete 在底层通过 operator delete全局函数来释放空间。
/*
operator new:该函数实际通过malloc来申请空间,当malloc申请空间成功时直接返回;申请空间
失败,尝试执行空 间不足应对措施,如果改应对措施用户设置了,则继续申请,否则抛异常。
*/
void* __CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
{
// try to allocate size bytes
void* p;
while ((p = malloc(size)) == 0)
if (_callnewh(size) == 0)
{
// report no memory
// 如果申请内存失败了,这里会抛出bad_alloc 类型异常
static const std::bad_alloc nomem;
_RAISE(nomem);
}
return (p);
}
/*
operator delete: 该函数最终是通过free来释放空间的
*/
void operator delete(void* pUserData)
{
_CrtMemBlockHeader* pHead;
RTCCALLBACK(_RTC_Free_hook, (pUserData, 0));
if (pUserData == NULL)
return;
_mlock(_HEAP_LOCK); /* block other threads */
__TRY
/* get a pointer to memory block header */
pHead = pHdr(pUserData);
/* verify block type */
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
_free_dbg(pUserData, pHead->nBlockUse);
__FINALLY
_munlock(_HEAP_LOCK); /* release other threads */
__END_TRY_FINALLY
return;
}
/*
free的实现
*/
#define free(p) _free_dbg(p, _NORMAL_BLOCK)
通过上述两个全局函数的实现知道,operator new 实际也是通过 malloc 来申请空间,如果 malloc 申请空间成功就直接返回,否则执行用户提供的空间不足应对措施,如果用户提供该措施就继续申请,否则就抛异常;operator delete 最终是通过 free 来释放空间的。
但是,有些同学会产生疑问:为什么不直接用 malloc ,而要用 operator new。
因为 malloc 失败会返回空,用 malloc 时要检查有没有成功;而 new 引出了一个叫做异常的东西(先简单了解一下):
#include <iostream>
using namespace std;
double Division(int a, int b)
{
// 当b == 0时抛出异常
if (b == 0)
throw "Division by zero condition!";
else
return ((double)a / (double)b);
}
void Func()
{
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;
}
int main()
{
try
{
Func();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
catch (...)
{
cout << "unkown exception" << endl;
}
return 0;
}
#include <iostream>
using namespace std;
struct ListNode
{
ListNode* _next;
int _val;
ListNode(int val)
:_next(nullptr)
, _val(val)
{}
};
void func()
{
//new失败了,抛异常,不需要再检查返回值
ListNode* n1 = new ListNode(1);
ListNode* n2 = new ListNode(2);
ListNode* n3 = new ListNode(3);
int* p1 = new int[100 * 1024 * 1024];
int* p2 = new int[100 * 1024 * 1024];
int* p3 = new int[100 * 1024 * 1024];
int* p4 = new int[100 * 1024 * 1024];
int* p5 = new int[100 * 1024 * 1024];
int* p6 = new int[100 * 1024 * 1024];
n1->_next = n2;
n2->_next = n3;
delete n1;
delete n2;
delete n3;
}
int main()
{
try
{
func();
}
catch (const exception& e)
{
cout << e.what() << endl;
}
return 0;
}
因此, operator new 是 malloc + 失败抛异常,它是为了封装 malloc;operator delete 是为了配对,就是把 free 封装一下。
如果申请的是内置类型的空间,new 和 malloc,delete 和 free 基本类似,不同的地方是:new/delete申请和释放的是单个元素的空间,new[] 和 delete[] 申请和释放的是连续空间,而且 new 在申请空间失败时会抛异常,malloc 会返回 NULL。
#include <iostream>
using namespace std;
class A
{
public:
A(int a = 0)
:_a(a)
{
cout << "A(int a)" << endl;
}
A(int a1, int a2)
{
cout << "A(int a1, int a2)" << endl;
}
A(const A& aa)
:_a(aa._a)
{
cout << "A(const A& aa)" << endl;
}
A& operator=(const A& aa)
{
cout << "A& operator=(const A& aa)" << endl;
if (this != &aa)
{
_a = aa._a;
}
return *this;
}
~A()
{
cout << "~A()" << endl;
}
private:
int _a;
};
#include <stack>
int main()
{
//operator new->(malloc) + 构造函数
A* p2 = new A;
//析构 + operator delete
delete p2;
stack<int>* p3 = new stack<int>;
delete p3;
return 0;
}
#include <iostream>
using namespace std;
class A
{
public:
A(int a = 0)
: _a(a)
{
cout << "A():" << this << endl;
}
~A()
{
cout << "~A():" << this << endl;
}
private:
int _a;
};
//结论:不要错配使用,一定匹配使用,否则结果是不确定
int main()
{
//A* p1 = new A;
A* p2 = new A[10]; //44 or 40 取决于有没有定义析构函数
//free(p2);//err
delete[] p2;
//delete p2;//err
int* p3 = new int[10]; //40
//free(p3);
return 0;
}
定位new表达式是在已分配的原始内存空间中调用构造函数初始化一个对象。
使用格式: new(place_address)type 或者 new(place_address)type(initializer-list)
place_address必须是一个指针,initializer-list是类型的初始化列表
#include <iostream>
using namespace std;
class A
{
public:
A(int a = 0)
: _a(a)
{
cout << "A():" << this << endl;
}
~A()
{
cout << "~A():" << this << endl;
}
private:
int _a;
};
int main()
{
//A* p1 = new A;
A* p1 = (A*)operator new(sizeof(A));
//p1->A();//不支持这样显式调用构造
//new(p1)A;//对已有空间,显式调用构造
new(p1)A(10);//对已有空间,显式调用构造
//delete p1;
p1->~A();
operator delete(p1);
//new []
A* p2 = (A*)operator new[](sizeof(A) * 10);
//new(p2)A[10]{ 1, 2, 3, 4 };
//以上写法也可以,但是最好用循环来写
for (int i = 0; i < 10; ++i)
{
new(p2 + i)A(i);
}
//delete[]
for (int i = 0; i < 10; i++)
{
(p2 + i)->~A();
}
operator delete[](p2);
return 0;
}
使用场景: 定位new表达式在实际中一般是配合内存池使用。因为内存池分配出的内存没有初始化,所以如果是自定义类型的对象,需要使用new的定位表达式进行显式调构造函数进行初始化。
malloc/free 和 new/delete 的共同点是:都是从堆上申请空间,并且需要用户手动释放。
不同的地方是: