c++ new 和 malloc 分配内存

创建一个类

cpp 复制代码
class Test {
public:
    Test() { std::cout << "constructor"; }
    virtual ~Test() {}

    void print() { std::cout << "a:" << a; }

private:
    int a = 10;
};

main函数

cpp 复制代码
int main(int argv, char **args)
{
    std::cout << "class size:" << sizeof(Test);
    void *ptr = ::malloc(sizeof(Test));

    std::cout << "new class";
    new (ptr) Test;
    
    std::cout << "convert";
    Test *test = (Test *)ptr;
    test->print();

    delete test;
    ::free(ptr);
    return 0;
}

输出

bash 复制代码
class size: 16 
new class 
constructor 
convert
a: 10 
free(): double free detected in tcache 2
Aborted (core dumped)

这里例子通过malloc分配了 class Test需要的内存空间
new (ptr) Test实际上就是将ptr内存分配给了class Test

可以看到调用了new (ptr) Test后, 就调用了class Test的构造函数

通过 Test *test = (Test *)ptr

ptr转换class Test

就可以调用class Test的函数

最后可以看到当调用delete test后再调用::free(ptr)

就触发了
free(): double free detected in tcache 2
Aborted (core dumped)

所以ptrclass Test访问的都是同一块内存

这就是内存池一个大致的原理

通过预先申请一块, 每当new的时候, 就是将预先申请的内存分配给class

delete的时候, 只是程序回收了这个内存块, 不是返还给系统

再看一个例子, 将class修改一下

bash 复制代码
class Test {
public:
    Test(int _A) : a(_A) { std::cout << "constructor"; }
    virtual ~Test() { std::cout << "destructor, a: " << a; }
    void print() { std::cout << "a:" << a; }

private:
    int a;
};

main函数

cpp 复制代码
int main(int argv, char **args)
{
    std::cout << "class size:" << sizeof(Test);
    void *ptr = ::malloc(sizeof(Test) * 10);

    new (ptr) Test(10);
    Test *test = (Test *)ptr;
    test->print();

    new ((void *)((Test *)ptr + sizeof(Test))) Test(20);
    Test *test2 = ((Test *)ptr + sizeof(Test));
    test2->print();

    delete test;
    delete test2;
    ::free(ptr);
    return 0;
}

输出

bash 复制代码
class size: 16 
constructor 
a: 10 
constructor 
a: 20 
destructor, a:  10 
destructor, a:  20 
free(): invalid pointer
Aborted (core dumped)
相关推荐
HMBBLOVEPDX几秒前
C++(深拷贝和浅拷贝)
开发语言·c++·浅拷贝和深拷贝
UrSpecial40 分钟前
Linux线程
linux·开发语言·c++
郝学胜-神的一滴41 分钟前
深入浅出 C++20:新特性与实践
开发语言·c++·程序人生·算法·c++20
汉克老师1 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.1.15]第二部分编程题(2 、寻宝石)
c++·蓝桥杯·蓝桥杯c++·c++蓝桥杯·蓝桥杯选拔赛
大锦终1 小时前
【Linux】进程间通信
linux·运维·服务器·c++
闪电麦坤951 小时前
C/C++项目练习:命令行记账本
开发语言·c++
菜就多练,以前是以前,现在是现在1 小时前
Codeforces Round 1048 (Div. 2)
数据结构·c++·算法
野生的编程萌新2 小时前
【C++深学日志】从0开始的C++生活
c语言·开发语言·c++·算法
木心爱编程2 小时前
C++程序员速通C#:从Hello World到数据类型
c++·c#
ulias2122 小时前
单元最短路问题
数据库·c++·算法·动态规划