malloc无法调用构造函数


#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class a{
    public:
        a();
        ~a();
        void s();
};
a::a(){
    cout<<"构造函数"<<endl;
}
a::~a(){
    cout<<"析构函数"<<endl;
}
void a::s(){
    cout<<"ddd"<<endl;
}
int main(){
    a* p1=(a*)malloc(sizeof(a));
    p1->s();
    free(p1);
    return 0;
} 

想问为什么我的程序无法调用构造函数和析构函数?

img

malloc函数只做内存申请操作,不做调用操作。
要想调用,建议不使用malloc
直接使用
a a2;
a2.s();

或者使用new的方式,参考链接:
https://blog.csdn.net/KAIFAWORD/article/details/52921974?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_ecpm_v1~rank_v31_ecpm-2-52921974.pc_agg_new_rank&utm_term=%E4%BD%BF%E7%94%A8malloc%E6%9E%84%E9%80%A0%E7%B1%BB%E5%AF%B9%E8%B1%A1%E4%B8%8D%E4%BC%9A%E8%B0%83%E7%94%A8%E5%AE%83%E7%9A%84%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0&spm=1000.2123.3001.4430

malloc 是从C语言继承过来的。参考 C++ Core Guidelines:

R.10: Avoid malloc() and free()
malloc() and free() do not support construction and destruction, and do not mix well with new and delete .