C ++ - 析构函数的调用次数比预期的多

时间:2017-08-25 12:20:36

标签: c++ oop constructor destructor

考虑以下代码:

class C1
{   public:

        C1(){ cout<<"CONSTR WAS HERE"<<endl; }

        C1(const C1&ob){ cout<<"COPY CONSTR WAS HERE"<<endl; }

        ~C1(){ cout<<"DESTR WAS HERE"<<endl; }
}

void f1(C1 x){  }

int main()
{
    C1 c1;
    f1(c1);
}

如果我们按原样运行代码,我们会得到:

CONSTR WAS HERE
COPY CONSTR WAS HERE
DESTR WAS HERE
DESTR WAS HERE

从我的观点来看,这是完全可以理解的。但是,如果我们将函数“f1”修改为:

  

C1 f1(C1 x){}

而不是

  

void f1(C1 x){}

我们得到:

CONSTR WAS HERE
COPY CONSTR WAS HERE
DESTR WAS HERE
DESTR WAS HERE
DESTR WAS HERE

我不太清楚为什么。

2 个答案:

答案 0 :(得分:12)

启用警告:

  

警告:函数返回非void [-Wreturn-type]

时没有return语句

您的计划中有undefined behavior,这意味着任何事情都可能发生。编译器可能“在这里返回C1的未定义实例”,这会导致析构函数被调用。

程序可能会崩溃或其他任何,具体取决于您的编译器/标志/机器。

答案 1 :(得分:9)

修改C1 f1(C1 x){}以实际返回某些内容,您的输出将符合预期(Demo

C1 f1(C1 x){ return {};}
  

CONSTR WAS HERE
  COPY CONSTR WAS HERE
  CONSTR WAS HERE
  DESTR就在这里
  DESTR就在这里
  DESTR就在这里

否则您的代码会显示未定义的行为。