C++ 删除由placement new创建的变异派生模板类实例
对于反序列化过程,我编写了一个基类,它根据序列化的数据变化为派生类。为了实现这一点,我使用了placement new操作符。在我尝试删除该实例之前,一切正常。我尝试过不同的方法,但每次都会出现堆损坏错误。我已经创建了一个简单的示例代码来展示我的方法 我正在使用VisualStudio2010 下面是演示问题的小示例代码: 标题.hC++ 删除由placement new创建的变异派生模板类实例,c++,visual-studio-2010,C++,Visual Studio 2010,对于反序列化过程,我编写了一个基类,它根据序列化的数据变化为派生类。为了实现这一点,我使用了placement new操作符。在我尝试删除该实例之前,一切正常。我尝试过不同的方法,但每次都会出现堆损坏错误。我已经创建了一个简单的示例代码来展示我的方法 我正在使用VisualStudio2010 下面是演示问题的小示例代码: 标题.h #pragma once #include <type_traits> class BaseClass { private: int _so
#pragma once
#include <type_traits>
class BaseClass
{
private:
int _someValue;
BaseClass(const BaseClass &other); // remove copy constructor
BaseClass(BaseClass &&other); // remove move constructor
BaseClass &operator=(const BaseClass &other); // remove assignment operator
public:
BaseClass(void);
virtual ~BaseClass(void);
void ChangeType(bool b);
};
template<typename T>
class DerivedClass : public BaseClass
{
private:
T _someMoreData;
DerivedClass(const DerivedClass &other); // remove copy constructor
DerivedClass(DerivedClass &&other); // remove move constructor
DerivedClass &operator=(const DerivedClass &other); // remove assignment operator
public:
DerivedClass(void) :
_someMoreData(0)
{
static_assert(std::is_same<T, int>::value || std::is_same<T, long>::value, "DerivedClass must be used with 'int' or 'long'.");
}
virtual ~DerivedClass(void)
{}
};
如何以干净的方式删除这些实例?派生类比基类大,新的位置不可能有效。你为什么要用继承来做这件事?谢谢你的提示!异常的原因是
BaseClass
和DerivedClass
的大小不同。在我更改了DerivedClass
的大小以适应BaseClass
的大小之后,一切都按预期工作。我只使用placement new操作符,因为它简化了代码中的内容。不幸的是,将现有代码重写为继承和工厂方法会很复杂。
#include <stdio.h>
#include <memory>
#include <tchar.h>
#include "Header.h"
BaseClass::BaseClass() :
_someValue(0)
{}
BaseClass::~BaseClass()
{}
void BaseClass::ChangeType(bool b)
{
this->~BaseClass();
if (b)
new (this) DerivedClass<int>();
else
new (this) DerivedClass<long>();
}
int _tmain(int argc, _TCHAR* argv[])
{
BaseClass *pBC = new BaseClass();
DerivedClass<int> *pDC = nullptr;
pBC->ChangeType(true);
pDC = reinterpret_cast<DerivedClass<int> *>(pBC);
// work with pDC ...
// 1st try:
delete pBC; // ERROR: Heap Corruption
// 2nd try:
pBC->~BaseClass();
::operator delete(pBC); // ERROR: Heap Corruption
// 3rd try:
pDC->~DerivedClass();
::operator delete(pDC); // ERROR: Heap Corruption
return 0;
}
HEAP CORRUPTION DETECTED: after Normal block (#111) at 0x004D6970.
CRT detected that the application wrote to memory after end of heap buffer.