如何解决C ++复制/移动和析构函数调用
在下面的示例中,试图理解为什么析构函数仅被调用两次:
#include <iostream>
#include <vector>
using namespace std;
class myclass{
public:
int a,b,c;
vector<int> mvec;
~myclass(){
cout << "getting destroyed ...\n";
}
};
myclass factory_method(){
myclass a {9,99,999,{0,1,2,3}};
//cout << a;
return a;
}
void test_func(){
cout << "====\n";
myclass b = factory_method();
myclass c {b};
}
int main (){
test_func();
return 0;
}
// prints the following
//====
//getting destroyed ...
//getting destroyed ...
据我了解,编译器会生成复制/移动构造函数和赋值函数,我可以看到它们的正常运行。
但是在这段代码中,我正在堆栈中创建3个对象,factory_method
中有1个对象(移动了,我明白了)。当对象a
的堆栈框架被破坏时,对象test_func
将被破坏,然后在b
中,对象factory_method
从c
移到,并创建对象b
由编译器在对象b
上生成副本构造函数。当c
堆栈帧被破坏时,对象test_func
和{{1}}都应被破坏,我应该看到3条“ getting destroy”消息。
我只有两个,我错过了什么吗?有人可以解释吗?
谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。