wht0408 2022-04-27 22:29 采纳率: 33.3%
浏览 56
已结题

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

  • 写回答

2条回答 默认 最新

  • ljhm 2022-04-28 20:20
    关注

    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 .

    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 5月7日
  • 已采纳回答 4月29日
  • 创建了问题 4月27日

悬赏问题

  • ¥15 ORBSLAM2框架跑ICL-NUIM数据集
  • ¥15 在我想检测ros是否成功安装时输入roscore出现以下
  • ¥30 老板让我做一个公司的投屏,实时显示日期,时间,安全生产的持续天数,完全没头绪啊
  • ¥15 Google Chrome 所有页面崩溃,三种解决方案都没有解决,我崩溃了
  • ¥20 使用uni-app发起网络请求,获取重定向302返回的cookie
  • ¥20 手机外部浏览器拉起微信小程序支付 (相关搜索:微信小程序)
  • ¥20 怎样通过一个网址找到其他同样模版的网址
  • ¥30 XIAO esp32c3 读取FDC2214的数据
  • ¥15 在工控机(Ubuntu系统)上外接USB蓝牙硬件进行蓝牙通信
  • ¥15 关于PROCEDURE和FUNCTION的问题