什么是空析构函数? [英] What does empty destructor do?
问题描述
我听说空析构函数不做任何事情,并且调用它不会删除对象。
但是在代码中:
I heard that empty destructor doesn't do anything and calling it doesn't remove the object. But in the code:
#include <iostream>
#include <set>
class a
{
public:
~a()
{}
std::set <int> myset;
};
int main()
{
a object;
object.myset.insert(55);
object.~a();
object.myset.insert(20);
std::cout << object.myset.size();
}
我得到:
* glibc detected * / strong> /.app:double free or corruption(fasttop):and thenABORT。
I get: "* glibc detected * /.app: double free or corruption (fasttop):" and then "ABORT".
如果重要的话我启用了c ++ 11标志。那么什么是空构造函数实际上做什么?
If it matters I have c++11 flag enabled. So what does empty constructor actually do? It does something and I read it doesn't.
推荐答案
你的析构函数可能看起来是空的,但它实际上是破坏了成员变量。在这种情况下,它会破坏 myset
,因此后续的 insert(20)
会崩溃。
Your destructor may look empty, but it's actually destructing the member variables. In this case, it's destructing myset
, so the subsequent insert(20)
is crashing.
如果你的类没有非POD成员变量,那么空析构函数将不会做任何事情。
If your class had no non-POD member variables then the empty destructor would truly do nothing.
这篇关于什么是空析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!