如何调用销毁功能?

时间:2016-04-25 10:46:59

标签: c++ constructor destructor

#include<iostream>
using namespace std;
class Monster {

  public: 
  Monster() {cout << "with out argument. \n";}
  Monster(int sz) { cout << "Monster created.\n"; }
  ~Monster() { cout << "Monster destroyed.\n"; }

  int GetSize() { return itsSize; }
  void SetSize(int str) { itsSize = str; }

private:
  int itsSize;
};

int main()
{
  Monster *m;
  m =new Monster[3];
  for(int i = 0; i < 3; i++)
     m[i] = i; // constructor with argument is getting called for each elements after which why destructor is getting called for each element.          
  delete []m;
  return 0;
}

Output:
with out argument. 
with out argument. 
with out argument. 
Monster created. // Monster constructor with argument is getting called.
Monster destroyed. // 1. Why this destructor is getting called after each call of constructor.
Monster created.
Monster destroyed. //2.
Monster created.
Monster destroyed. //3.
Monster destroyed.
Monster destroyed.
Monster destroyed.

当我用值初始化Array of Monster对象时,会调用参数化构造函数,之后会立即调用析构函数?

1 个答案:

答案 0 :(得分:6)

m =new Monster[3];

这里创建了三个对象,为每个对象调用了默认构造函数。这就是您看到邮件with out argument.

的原因
m[i] = i;

首先,使用Monster(int)构造函数在右侧创建临时Monster。这就是您看到消息Monster created.的原因。接下来,调用赋值运算符。接下来,删除您的临时怪物。这就是您看到Monster destroyed.

的原因
delete []m;

阵列中的三个怪物被摧毁。

为了更好地了解此类情况,建议您在所有邮件中添加this的地址。