gpt4 book ai didi

c++ - 当我从 main 调用 ctor 时,为什么在范围结束之前调用 dtor? (实验性的)

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:38 25 4
gpt4 key购买 nike

在这里,我在 main() 中调用类 a 的构造函数,但没有创建该类的对象,看起来析构函数在调用后立即被调用。这里到底发生了什么?据我了解,这是因为我没有创建具有内存的对象吗? dtor 是如何在这里被调用的?它是如何实现的?请分享您对此的看法。

#include<iostream>
using namespace std;

class a{
public:
a(){
cout<<"\nctor";
}
~a(){
cout<<"\ndtor";
}
};

int main(){
a(); //why the dtor is getting called before the scope ends?
cout<<"\nctor_called\n";
}

程序的o/p:

ctor
dtor
ctor_called

最佳答案

您没有调用构造函数(您不能直接调用)。您正在构建一个立即销毁的临时对象。

尝试

a anA;

关于c++ - 当我从 main 调用 ctor 时,为什么在范围结束之前调用 dtor? (实验性的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22793900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com