为什么dtor在范围结束之前被调用,当我从主调用ctor? (实验) [英] why the dtor is getting called before the scope ends when I call the ctor from main? (Experimental)

查看:123
本文介绍了为什么dtor在范围结束之前被调用,当我从主调用ctor? (实验)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我在 main()中调用 的构造函数而不创建该类的对象它看起来析构函数被调用后立即被调用。这里发生了什么?根据我的理解,它发生,因为我没有创建一个对象与一些记忆?如何在这里调用dtor?如何实施?请分享您的想法。

Here I am calling the constructor of class a in main() without creating an object of that class and it looks the destructor is getting invoked immediately after the call. What is actually happening here? As per my understanding, it’s happening because I have not created an object with some memory? How the dtor is getting called here? How it is implemented? Please share your thoughts on this.

#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


推荐答案

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

You're not calling the constructor (you can't directly). You're constructing a temporary object which is immediately destroyed.

尝试

a anA;

这篇关于为什么dtor在范围结束之前被调用,当我从主调用ctor? (实验)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆