调用构造函数而不创建对象 [英] Calling a constructor without creating object

查看:134
本文介绍了调用构造函数而不创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码中到底发生了什么。

What exactly is happening in the code below.

#include<iostream.h>

class Demo
{
    public :

    Demo()
    {
        cout<<"\nIn Demo const";
    }
    ~Demo()
    {
        cout<<"\nin demo dest";
    }
};

void main() {
    Demo();
}

Demo()只需调用构造函数和析构函数即可。是否在此过程中创建对象?

Demo() simply calls the constructor and destructor. Is a object being created in this process? And thus is the memory being allocated?

推荐答案

您没有显式调用构造函数,而是这段代码创建了一个临时的未命名对象类型为 Demo ,在; 之后立即销毁。

You're not explicitly calling the constructor, instead this code creates a temporary unnamed object with type Demo, which is destroyed immediately after ;.

是的,为此临时对象分配了内存(自动在堆栈上),并在; 之后将其释放(再次自动)。同时,按预期方式调用了构造函数和析构函数。

Yes, memory is allocated (automatically, on the stack) for this temp object and it's freed (again automatically) after ;. Meanwhile, the constructor and destructor are called, as expected.

这篇关于调用构造函数而不创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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