C++内存管理:其三、new和delete的行为拆分

new和delete都是C++的关键字,不可重载。其底层的行为可以看作多个函数的组合。

一、自己实现new与delete的功能

cpp 复制代码
#include <iostream>
using namespace std;

class Student{
private:
    int age{24};
public:
    Student(){
        cout<<"start"<<endl;
    }

    ~Student(){
        cout<<"end"<<endl;
    }

    void f(){
        cout<<"age = "<<age<<endl;
    }
};

int main(void) {
    Student * p = (Student *)operator new(sizeof(Student));    //自己实现new
    new(p) Student;

    p->f();

    p->~Student();          //自己实现delete
    operator delete(p);

    return 0;
}

第一行:

Student * p = (Student *)operator new(sizeof(Student));

operator new是C++自带的函数,可以重载。准确调用方法是:

::operator new(sizeof(Student));

::表示全局命名空间,注意不是std::标准命名空间!

底层调用的是malloc函数,实际上返回的是void * 指针。参数表示要申请的字节数。

第二行:

new§ Student;

表示在给定的地址(堆上地址)执行构造函数。

对应delete的操作:

p->~Student();表示在某个地址上执行析构函数。

operator delete§;

调用的是C++自带的函数,同样可以重载。底层调用的是free()函数。

二、operator new和operator delete重载

相关推荐
Sylvia-girl3 小时前
Java——抽象类
java·开发语言
Yana.nice5 小时前
Bash函数详解
开发语言·chrome·bash
m0_535064606 小时前
C++模版编程:类模版与继承
java·jvm·c++
tomorrow.hello7 小时前
Java并发测试工具
java·开发语言·测试工具
晓13138 小时前
JavaScript加强篇——第四章 日期对象与DOM节点(基础)
开发语言·前端·javascript
老胖闲聊8 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
Tanecious.8 小时前
C++--红黑树封装实现set和map
网络·c++
她说人狗殊途9 小时前
java.net.InetAddress
java·开发语言
天使day9 小时前
Cursor的使用
java·开发语言·ai
Dxy12393102169 小时前
Python ExcelWriter详解:从基础到高级的完整指南
开发语言·python