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重载

相关推荐
熊猫钓鱼>_>1 天前
从零开始构建RPG游戏战斗系统:实战心得与技术要点
开发语言·人工智能·经验分享·python·游戏·ai·qoder
FuckPatience1 天前
C++ 常用类型写法和全称
开发语言·c++
q***R3081 天前
Kotlin注解处理
android·开发语言·kotlin
lly2024061 天前
C++ 数组
开发语言
csbysj20201 天前
C 强制类型转换
开发语言
m0_626535201 天前
代码分析
开发语言·c#
q***3751 天前
QoS质量配置
开发语言·智能路由器·php
__BMGT()1 天前
参考文章资源记录
开发语言·c++·qt
一晌小贪欢1 天前
【Python办公】用 Selenium 自动化网页批量录入
开发语言·python·selenium·自动化·python3·python学习·网页自动化
ouliten1 天前
C++笔记:std::string_view
开发语言·c++·笔记