【问题标题】:Why destructor is being called but construction not being called when passing object as a parameter? [closed]为什么将对象作为参数传递时调用析构函数但不调用构造函数? [关闭]
【发布时间】:2015-04-10 05:11:55
【问题描述】:

如果我编写一个名为 Testclass 并编写一个 Test type show() 函数,例如

#include <iostream>
using namespace std;

class Test{

public:
    int x;
    Test()
    {
        cout<<"Empty or Default Constructor"<<endl;
    }
    Test(int x)
    {
        cout<<"Valued constructor"<<endl;
    }
    ~Test()
    {
        cout<<"Destructor"<<x<<endl;
    }
    Test show(Test obj)
    {
        Test tt;
        tt.x=20;
        return tt;
    }
};
int main()
{
    Test t1,t2(20);
    t2.show(t2);

    return 0;
}

输出:

Empty or Default Constructor
Valued constructor
Empty or Default Constructor
Destructor : 20
Destructor : 1988276941
Destructor : 1988276941
Destructor : 1972875622

然后输出显示 Test objreturn tt 的析构函数,但没有为它们创建构造函数,但通常我们知道首先会创建构造函数并在完成任务后析构函数将被调用,但为什么在传递和返回任何对象时异常?

【问题讨论】:

  • 在“测试 tt;”中将调用 Test 的默认构造函数(如果存在),但由于您不提供 Test 的代码,因此无法回答。另外,请注意,根本没有使用 obj,因此编译器不妨将其优化掉。
  • 完整编写代码并显示您正在打印的位置。
  • @DanielDaranas,你能告诉我为什么构造函数没有被调用 Test obj 并返回 tt。
  • @RazibHossainShuvo。不,我拒绝分析这样的代码。对不起,但这没有任何意义。

标签: c++ constructor destructor


【解决方案1】:

通过值传递类的实例会调用复制构造函数。

如果类定义没有显式提供复制构造函数,则编译器默认实现复制构造函数(本质上是调用任何基类的复制构造函数后的成员复制)。此编译器生成的复制构造函数不会调用您已实现的其他构造函数之一,因此构造副本不会打印任何内容。但是,完成后将调用析构函数来清理副本。

在你的类中,如果你实现一个拷贝构造函数如下;

Test(const Test &from) : x(from.x)
{
    std::cout << "Copy constructor invoked" << std::endl;
}

你会发现复制构造函数确实被调用了。

【讨论】:

    猜你喜欢
    • 2019-12-16
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2021-04-01
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多