无法调用使用 malloc/placement new 创建的类上的虚函数



我尝试为我的自定义分配器编写新的/删除函数,但是每当调用虚拟函数时,使用放置新初始化的对象都会抛出"访问冲突执行位置"。

当我尝试分配同一类的两个对象时,一个带有 new 对象,一个带有放置 new,它们的 vptrs 指向相同的函数,但只有使用 new 创建的对象才能执行该函数。

//Definition not shown
class Component
{
public:
    Component() {}
    virtual void Update() {}
    virtual void Init() {}

};
//Definition not shown
class MeshComponent :
    public Component
{
public:
    virtual void Update() override;
    virtual void Init() override;
};

#define fnew(T,...) new (malloc(sizeof(T))) T (__VA_ARGS__);
MeshComponent* newComponent = fnew(MeshComponent);
MeshComponent* newComponent2 = new MeshComponent();
newComponent2->Update(); //Runs like expected
newComponent->Update();  //Access violation executing location

知道这是为什么吗?

好吧,

我重新启动了Visual Studio,它现在可以工作了...谢谢大家的见解。

最新更新