如here所示如何检测指示器的删除,可以使用dynamic_cast
以检测删除指针:使用动态铸造
#include <iostream>
using namespace std;
class A
{
public:
A() {}
virtual ~A() {}
};
class B : public A
{
public:
B() {}
};
int main()
{
B* pB = new B;
cout << "dynamic_cast<B*>(pB) ";
cout << (dynamic_cast<B*>(pB) ? "worked" : "failed") << endl;
cout << "dynamic_cast<B*>((A*)pB) ";
cout << (dynamic_cast<B*>((A*)pB) ? "worked" : "failed") << endl;
delete pB;
cout << "dynamic_cast<B*>(pB) ";
cout << (dynamic_cast<B*>(pB) ? "worked" : "failed") << endl;
cout << "dynamic_cast<B*>((A*)pB) ";
cout << (dynamic_cast<B*>((A*)pB) ? "worked" : "failed") << endl;
}
输出:
dynamic_cast<B*>(pB) worked
dynamic_cast<B*>((A*)pB) worked
dynamic_cast<B*>(pB) worked
dynamic_cast<B*>((A*)pB) failed
它解释说检测到vtable的删除。
但我想知道如何可能,因为我们不覆盖释放的内存?
而且该解决方案是否完全可移植?
感谢
我猜''dynamic_cast'使用[RTTI](http://en.wikipedia.org/wiki/Run-time_type_information)来验证被转换为的类型。 –
我怀疑这是平台依赖的行为。 –
Visual Studio 2013使用此代码抛出“__non_rtti_object”异常。 –