通过使用智能指针阅读访问违规行为

Read Access Violation From Using Smart Pointers

本文关键字:读访问 指针 智能      更新时间:2023-10-16

这个问题已经困扰着我几天了,我只是无法弄清楚。我要做的是从实体图中获取一个实体,然后副本的副本。实体本质上是组件的地图,因此我遍布每个组件并制作了它的副本。我调试了该程序,直到最后一行,它效果很好,它说"阅读访问侵犯 this 是0xfffffffffffffffffffffffff7。"这很奇怪,因为所有内容都已初始化(我检查了调试器)

if (entityMap.find(classname) != entityMap.end()) {
    std::shared_ptr<Entity> & prefab = entityMap[classname];
    std::shared_ptr<Entity> entity = std::shared_ptr<Entity>(new Entity());
    for (auto & component : prefab->GetComponentMap()) {
        Component * compPtr = component.second.get();
        std::cout << compPtr->GetMemorySize() << "n";
        size_t size = sizeof(compPtr->GetMemorySize());
        void * buffer = operator new(size);
        memcpy(buffer, compPtr, size);
        std::shared_ptr<Component> newComponent = std::shared_ptr<Component>(reinterpret_cast<Component *>(buffer));
        entity->AddComponent(newComponent);
        newComponent->SetOwner(entity);
    }

这是有问题的线

 newComponent->SetOwner(entity);

这就是一切,将所有者实例变量设置为参数中传递的变量。那是调试器抱怨的地方,并派我在_decref方法上提交"内存"。

void Component::SetOwner(std::shared_ptr<Entity> owner) {
    this->owner = owner;
}

这里的问题是,您不能仅复制内存来复制对象。对于没有任何构造函数,破坏者或指针的基本普通数据对象,此可以使用,但对于更复杂的任何事情都可能不会。

例如,如果对象包含数据指针,并且这些指示符在毁灭仪中释放,则数据不会被深入复制,而是指针是,并且您将获得双免费的,也可能会以未分配的内存。如果对象依赖于构造函数中所做的操作,则在复制内存时永远不会完成。并且根据如何计算大小的不同,它甚至可能不是完整的副本。

这就是为什么您应该始终在课堂中提供克隆机制,以适合对象的方式来照顾这些问题,并确保根据内容的不同而确保有适当的深/浅复制。