#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

本文探讨了C++中使用new与malloc分配内存的区别,特别是针对类实例化时构造函数的调用与否进行了详细说明,并通过示例展示了不同内存分配方式的影响。
785

被折叠的 条评论
为什么被折叠?



