通过使用智能指针阅读访问违规行为
Read Access Violation From Using Smart Pointers
这个问题已经困扰着我几天了,我只是无法弄清楚。我要做的是从实体图中获取一个实体,然后副本的副本。实体本质上是组件的地图,因此我遍布每个组件并制作了它的副本。我调试了该程序,直到最后一行,它效果很好,它说"阅读访问侵犯 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;
}
这里的问题是,您不能仅复制内存来复制对象。对于没有任何构造函数,破坏者或指针的基本普通数据对象,此可以使用,但对于更复杂的任何事情都可能不会。
例如,如果对象包含数据指针,并且这些指示符在毁灭仪中释放,则数据不会被深入复制,而是指针是,并且您将获得双免费的,也可能会以未分配的内存。如果对象依赖于构造函数中所做的操作,则在复制内存时永远不会完成。并且根据如何计算大小的不同,它甚至可能不是完整的副本。
这就是为什么您应该始终在课堂中提供克隆机制,以适合对象的方式来照顾这些问题,并确保根据内容的不同而确保有适当的深/浅复制。
相关文章:
- C++ - 循环访问指针数组会导致错误
- 如何访问指针结构的成员变量?
- 从子线程访问指针
- 如何在C++中使用类对象访问指针数据成员
- 如何使用二维语法访问指针
- 我可以保证以负偏移访问指针吗?
- 是否访问指针元组和互斥锁线程安全
- 如何从嵌套类中访问指针
- C++ 如何访问指针的结构变量
- 从地图擦除后访问指针
- 会员在共享_ptr上访问指针
- 删除后访问指针
- 为什么在递增后使用 [] 运算符访问指针数组会返回错误地址的当前内存位置
- 如何在python脚本中使用Pybind11修改/访问C++指针
- 无法从另一个函数访问指针数组
- 无法访问指针C 的值
- 访问指针类成员 (C++)
- 访问指针数组中的子类方法
- 访问指针到结构中的向量
- 访问指针类型的静态属性