创建指针时是否没有构造函数调用

Is there no constructor call when pointer is created?

本文关键字:函数调用 指针 是否 创建      更新时间:2023-10-16

当我运行这个程序时,类 A 的析构函数被调用了两次,但构造函数被调用了一次。

#include<iostream>
using namespace std;
class A{
public:
    A(){cout<<"constructorn";}
    ~A(){cout<<"destructorn";}
};
int main()
{
    A a1;
    A *ap=&a1;
    delete ap;
return 0;
}

输出:

constructor
destructor
destructor

a1是一个普通的旧变量,所以当你声明它时,构造函数被调用。 ap是一个指针变量,因此声明它或分配给它不会调用任何构造函数。 ap只是指向a1的指针。

显式删除ap时,将调用析构函数,当a1超出范围时,将再次调用析构函数。如注释中所述,在未使用 new 初始化的指针上调用 delete 是错误的,并且将导致未定义的行为。