C/C++ new,malloc

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
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.csdn.net/qq_40840459/article/details/81268252

你可能感兴趣的:(C/C++知识,C++,c++,计算机视觉,opencv)