【发布时间】:2019-11-24 11:48:11
【问题描述】:
我想销毁模板化的对象,但保持分配的内存被填充。不幸的是,对象的析构函数永远不会被调用,并且单步执行代码,它会跳过手动调用。
#include <iostream>
template <typename type> class TestClass
{
private:
type *data;
public:
TestClass();
~TestClass();
template <typename T> void Set(T &&element);
void Replace();
};
template <typename type> TestClass<type>::TestClass()
{
data = reinterpret_cast<type *>(new char[sizeof(type)]);;
}
template <typename type> TestClass<type>::~TestClass()
{
}
template <typename type> template <typename T> void TestClass<type>::Set(T &&element)
{
new(data) type(static_cast<T &&>(element));
}
template <typename type> void TestClass<type>::Replace()
{
type *pointer = reinterpret_cast<type *>(&data[0]);
pointer->~type();
//Fill with data
}
class MyClass
{
public:
MyClass()
{
}
~MyClass()
{
std::cout << "Called" << "\n";
}
};
int main()
{
MyClass *myClass = new MyClass();
TestClass<MyClass *> myObject;
myObject.Set(myClass);
myObject.Replace();
return 0;
}
我已经在 VS 2017 和在线 C++ 编译器上对此进行了测试。两者都跳过了指针->~type();当单步执行时,析构函数永远不会被调用。
编辑:重写代码,现在重现错误。
【问题讨论】:
-
我们可以得到minimal reproducible example吗?
-
我已经更新了代码以显示精简版本,但就能够编译它而言,恐怕需要做一些工作。
标签: c++ pointers templates destructor