为什么我的析构函数似乎比构造函数更频繁地被调用? [英] Why does my destructor appear to be called more often than the constructor?
问题描述
#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 $
#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屋!