为什么我的析构函数似乎比构造函数更频繁地被调用? [英] Why does my destructor appear to be called more often than the constructor?

查看:145
本文介绍了为什么我的析构函数似乎比构造函数更频繁地被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #include< istream> 
using namespace std;

class A {
public:
static int cnt;
A()
{
++ cnt;
cout<<constructor:<< cnt<< endl;
}
〜A()
{
--cnt;
cout <<destructor:<< cnt<< endl;
}
};

int A :: cnt = 0;

A f(A x){
return x;
}
int main(){
A a0;
A a1 = f(a0);
return 0;
}

程序将输出:


$ b b

 
constructor:1
destructor:0
destructor:-1
destructor:-2

构造函数和析构函数不会成对出现?

解决方案

复制构造函数增加计数器。

  A(const A&)
{
++ cnt;
cout<<copy constructor:<< cnt<< endl;
}

如果不明确添加它,



此表达式

  A a1 = f(a0); 

正在创建 a0 的副本使用复制构造函数。确切的份数可能会有所不同,具体取决于复制准确,但您的 cnt 注意:在 中, C ++ 11,你也应该考虑编译器生成 move copy constructor 的可能性,但是,一旦你声明你自己的拷贝构造函数,编译器就不再产生move版本。


#include<iostream>
using namespace std;

class A{
public:
    static int cnt;
    A()
    { 
        ++cnt; 
        cout<<"constructor:"<<cnt<<endl;
    }
    ~A()
    {
        --cnt;
        cout<<"destructor:"<<cnt<<endl;
    }
};

int A::cnt = 0;

A f(A x){
    return x;
}
int main(){
    A a0;
    A a1 = f(a0);
    return 0;
}

The program will output:

constructor:1
destructor:0
destructor:-1
destructor:-2

The constructor and destructor don't appear in pairs?

解决方案

You need to add a copy constructor that increases the counter.

A(const A&)
{ 
    ++cnt; 
    cout<<"copy constructor:"<<cnt<<endl;
}

If you don't add it explicitly, the compiler generates one that does nothing with the counter cnt.

This expression

A a1 = f(a0);

is creating copies of a0, which make use of the copy constructor. The exact number of copies may vary depending on copy elision, but your cnt should be 0 at the end of the program.

Note: In C++11, you should also consider the possibility of a compiler generated move copy constructor, however, once you declare your own copy constructor, the compiler no longer generates the move version.

这篇关于为什么我的析构函数似乎比构造函数更频繁地被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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