创建指针时是否没有构造函数调用
Is there no constructor call when pointer is created?
当我运行这个程序时,类 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
是错误的,并且将导致未定义的行为。
相关文章:
- 使用共享指针的函数调用,其对象应为 const
- 返回指向对象的指针的函数调用是否为 prvalue?
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- 在结构外部调用指向函数的指针
- VkSurfaceKHR 指针的值在函数调用后更改,无需任何显式赋值
- 使用指向成员函数的指针在另一个类中调用类构造函数
- 指针在函数调用后更改其地址
- 努力将指向成员函数的指针绑定到类模板的T成员,然后在槽中调用
- 对std::函数对象的调用不匹配,该对象是指向成员函数的指针
- C++:这是使用整数变量作为函数调用指针的正确方法吗
- 正确的方法是什么?调用指针到指针到指针内部的函数?
- 参数的混合值,当我调用指针成员函数时
- 使用函数指针时,ESP 未在函数调用中正确保存
- 为什么使用指向函数的指针调用虚函数时不需要指针"this"?
- 函数调用歧义(用户定义的转换和 Derived2Base 指针转换)
- 创建指针时是否没有构造函数调用
- 调用指向成员函数的指针时出错
- 这些函数调用的返回指针的区别是什么?
- 如何通过指向返回另一个函数的函数的指针调用具有默认参数的函数
- 为什么我不能在插入的函数调用中直接使用返回的指针作为参数