【C++学习】C&C++内存管理

目录

一、C&C++内存管理

二、C语言中动态内存管理方式:malloc/calloc/realloc/free

三、C++内存管理方式

3.1 new/delete操作内置类型

3.2 new和delete操作符自定义类型

四、operator new与operator delete函数

4.1 operator new与operator delete函数(重点)

五、new和delete的实现原理

5.1 内置类型

5.2 自定义类型

六、定位new表达式(placement-new)


一、C&C++内存管理

我们先来看下面的一段代码和相关问题:
int globalVar = 1;
static int staticGlobalVar = 1;
void Test()
{
    static int staticVar = 1;
    int localVar = 1;
    int num1[10] = { 1, 2, 3, 4 };
    char char2[] = "abcd";
    const char* pChar3 = "abcd";
    int* ptr1 = (int*)malloc(sizeof(int) * 4);
    int* ptr2 = (int*)calloc(4, sizeof(int));
    int* ptr3 = (int*)realloc(ptr2, sizeof(int) * 4);
    free(ptr1);
    free(ptr3);
}
1. 选择题:
    选项:   A .       B .       C . 数据段 静态区)     D . 代码段 常量区
    globalVar 在哪里? ____           staticGlobalVar在哪里? ____
    staticVar 在哪里? ____           localVar在哪里? ____
    num1 在哪里? ____
    char2 在哪里? ____   * char2 在哪里? ___
    pChar3 在哪里? ____       * pChar3 在哪里? ____
    ptr1 在哪里? ____         * ptr1 在哪里? ____
2. 填空题:
    sizeof ( num1 ) = ____   
    sizeof ( char2 ) = ____         strlen ( char2 ) = ____
    sizeof ( pChar3 ) = ____        strlen ( pChar3 ) = ____
    sizeof ( ptr1 ) = ____
3. sizeof strlen 区别?

【说明】

  1. 又叫堆栈——非静态局部变量/函数参数/返回值等等,栈是向下增长的。
  2. 内存映射段是高效的I/O映射方式,用于装载一个共享的动态内存库。用户可使用系统接口创建共享共享内存,做进程间通信。
  3. 用于程序运行时动态内存分配,堆是可以上增长的。
  4. 数据段——存储全局数据和静态数据。
  5. 代码段——可执行的代码/只读常量。

二、C语言中动态内存管理方式:malloc/calloc/realloc/free

void Test ()
{
    int* p1 = (int*) malloc(sizeof(int));
    free(p1);
    // 1.malloc/calloc/realloc的区别是什么?
    int* p2 = (int*)calloc(4, sizeof (int));
    int* p3 = (int*)realloc(p2, sizeof(int)*10);
    // 这里需要free(p2)吗?
    free(p3 );
}

malloc的实现原理:Glibc中malloc实现原理

三、C++内存管理方式

        C语言内存管理方式在 C++ 中可以继续使用,但有些地方就无能为力,而且使用起来比较麻烦,因此C++ 又提出了自己的内存管理方式: 通过 new delete 操作符进行动态内存管理。

3.1 new/delete操作内置类型

void Test()
{
     // 动态申请一个int类型的空间
     int* ptr4 = new int;
  
     // 动态申请一个int类型的空间并初始化为10
     int* ptr5 = new int(10);
  
     // 动态申请10个int类型的空间
     int* ptr6 = new int[3];
     delete ptr4;
     delete ptr5;
     delete[] ptr6;
}

 

注意:申请和释放单个元素的空间,使用newdelete操作符,申请和释放连续的空间,使用new[]delete[]。注意:需要匹配起来使用。

3.2 new和delete操作符自定义类型

class A
{
public:
    A(int a = 0)
        : _a(a)
    {
        cout << "A():" << this << endl;
    }
    ~A()
    {
        cout << "~A():" << this << endl;
    }
private:
    int _a;
};
int main()
{
    // new/delete 和 malloc/free最大区别是 new/delete对于【自定义类型】除了开空间还会调用构造函数和析构函数
    A* p1 = (A*)malloc(sizeof(A));
    A* p2 = new A(1);
    free(p1);
    delete p2;
    // 内置类型是几乎是一样的
    int* p3 = (int*)malloc(sizeof(int)); // C
    int* p4 = new int;
    free(p3);
    delete p4;
    A* p5 = (A*)malloc(sizeof(A)*10);
    A* p6 = new A[10];
    free(p5);
    delete[] p6;
    return 0;
}
注意:在申请自定义类型的空间时, new 会调用构造函数, delete 会调用析构函数,而 malloc free 不会。

四、operator newoperator delete函数

4.1 operator newoperator delete函数(重点)

        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 来释放空间的

五、new和delete的实现原理

5.1 内置类型

        如果申请的是内置类型的空间,new malloc delete free 基本类似。
        不同的地方是:new/delete申请和释放的是单个元素的空间,new[] delete[] 申请的是连续空间,而且 new 在申请空间失败时会抛异常,malloc 会返回 NULL

5.2 自定义类型

  • new的原理
        1. 调用 operator new 函数申请空间。
        2. 在申请的空间上执行构造函数,完成对象的构造。
  • delete的原理
        1. 在空间上执行析构函数,完成对象中资源的清理工作。
        2. 调用 operator delete 函数释放对象的空间。
  • new T[N]的原理
        1. 调用 operator new[] 函数,在 operator new[] 中实际调用 operator new 函数完成 N 个对象空间的申请。
        2. 在申请的空间上执行 N 次构造函数。
  • delete[]的原理
        1. 在释放的对象空间上执行 N 次析构函数,完成 N 个对象中资源的清理。
        2. 调用 operator delete[] 释放空间,实际在 operator delete[] 中调用 operator delete 来释放空间。

六、定位new表达式(placement-new)

定位 new 表达式是在 已分配的原始内存空间中调用构造函数初始化一个对象
使用格式:
        new (place_address) type或者 new (place_address) type(initializer-list)
        place_address必须是一个指针, initializer-list 是类型的初始化列表
使用场景:
        定位new 表达式在实际中一般是配合内存池使用。因为内存池分配出的内存没有初始化,所以如果是自定义类型的对象,需要使用new 的定义表达式进行显示调构造函数进行初始化。
class A
{
public:
    A(int a = 0)
        : _a(a)
    {
        cout << "A():" << this << endl;
    }
    ~A()
    {
        cout << "~A():" << this << endl;
    }
private:
    int _a;
};

// 定位new/replacement new
int main()
{
    // p1现在指向的只不过是与A对象相同大小的一段空间,还不能算是一个对象,因为构造函数没有执行
    A* p1 = (A*)malloc(sizeof(A));
    new(p1)A;  // 注意:如果A类的构造函数有参数时,此处需要传参
    p1->~A();
    free(p1);
    A* p2 = (A*)operator new(sizeof(A));
    new(p2)A(10);
    p2->~A();
    operator delete(p2);
    return 0;
}
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cassooo_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值