C/C++ new,malloc

本文探讨了C++中使用new与malloc分配内存的区别,特别是针对类实例化时构造函数的调用与否进行了详细说明,并通过示例展示了不同内存分配方式的影响。
#include <thread>
#include <vector>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <thread>
#include <list>
#include <string>
using namespace std;

class cla{
public:
    int h;
    cla();
};
cla::cla(){
    h=10;
}

void foo(){
    cout<<"thread"<<endl;
}

typedef struct _strc{
    cla clas;
    cla * clas1 = new cla();
    cla * clas2 = (cla *)malloc(sizeof(cla));

    thread threadA;
    
}strc;



int main(){
    // 调用构造函数
    cla * P = new cla();
    cout<<P->h<<endl;
    // log: 10

    // 不会调用构造函数也不会赋值
    cla * PM = (cla *)malloc(sizeof(cla));
    cout<<PM->h<<endl;
    // log: 0

    // 调用构造函数  
    void * v = malloc(sizeof(cla));
    cla *PMM = new(v)cla;
    cout<<PMM->h<<endl;
    PMM->~cla();
    free(v);
    // log: 0

    cout<<"---------"<<endl;

    // new结构体 调用构造函数
    strc *snew = new strc();
    cout<<snew->clas.h<<endl;
    cout<<snew->clas1->h<<endl;
    cout<<snew->clas2->h<<endl;
    snew->threadA = thread(foo);
    // log: 10
    // log: 10
    // log: 0
    // log: thread

    cout<<"---------"<<endl;

    // malloc结构体 其中的class成员不会调用构造函数也不会赋值
    strc *smal = (strc *)malloc(sizeof(strc));
    cout<<smal->clas.h<<endl;
    cout<<smal->clas1->h<<endl; //!
    cout<<smal->clas2->h<<endl; //! 
    snew->threadA = thread(foo);//!
    // log: 0
    // log: Segmentation fault (core dumped)
    // log: Segmentation fault (core dumped)
    // log: Aborted (core dumped)

}

参考 :https://blog.youkuaiyun.com/qq_40840459/article/details/81268252

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值