析构函数问题



我最近读到,如果你使用类的对象作为函数的接收参数,则必须自动创建对象的副本。因此,如果析构函数包含在类中,则原始对象及其副本将自动消失。但是,当我尝试制作具有相同概念析构函数的小代码时,只激活了一次。什么会导致问题?提前感谢!

#include "stdafx.h"
#include <iostream>
using namespace std;
class MyClass {
int val;
public:
MyClass(int i)
{
val = i;
cout << "Constructor is in progress" << endl;
}
void SetVal(int i)
{
val = i;
}
int GetVal()
{
return val;
}
~MyClass()
{
cout << "Destructer is in progress" << endl;
}
};

void Display(MyClass obj)
{
cout << obj.GetVal();
}
int main()
{
MyClass a(10);
cout << "Before display()" << endl;
Display(a);
cout << "After display()" << endl;
system("pause");
return 0;
}

它在返回语句之后调用。您看到的第一条消息来自复制的对象。当您到达system("pause")原始对象仍在范围内时,因此不会调用析构函数。它在计算返回语句后调用。

在 main(( 末尾调用析构函数吗;奇怪的行为

最新更新