为什么在vector中的shared_ptr上调用方法会抛出运行时异常?
Why does calling a method on a shared_ptr in a vector throw a runtime exception?
为什么下面的代码会抛出
Exception thrown at 0x53A5C6DC (nvoglv32.dll) in RenderEngine.exe: 0xC0000005: Access violation reading location 0x0002B174.
在运行时,什么是一个好的解决方案?
std::vector<std::shared_ptr<Static>> statics;
void drawStatics() {
for (std::shared_ptr<Static> stat: statics) {
Static *statptr = stat.get();
statptr->Draw(); //This is what triggers the runtime exception.
}
}
void addStatic(Mesh &mesh, Texture &texture, Transform transform) {
statics.push_back(
std::make_shared<Static>(
mesh,
texture,
transform,
shader,
camera
));
}
int main() {
addStatic(playerMesh, playerTexture, platformTransform);
drawStatics();
return 0;
}
Static头文件如下:
#pragma once
#include "mesh.h"
#include "texture.h"
#include "transform.h"
#include "camera.h"
#include "shader.h"
class Static {
public:
Static(Mesh &mesh, Texture &texture, Transform &transform, Shader &shader, Camera &camera);
~Static();
void Draw();
private:
Mesh *mesh;
Texture *texture;
Transform *transform;
Shader *shader;
Camera *camera;
};
在静态源文件中,Draw()被实现为:
void Static::Draw() {
texture->Bind(0);
shader->Update(*transform, *camera);
mesh->Draw();
}
以及静态构造函数和解构函数:
Static::Static(Mesh &mesh, Texture &texture, Transform &transform, Shader &shader, Camera &camera)
:mesh(&mesh), texture(&texture), transform(&transform), shader(&shader), camera(&camera)
{}
Static::~Static() {}
编辑:我正在使用visual studio,如果这很重要。
这就是你在代码中抛出指针和引用而不考虑生命周期所得到的结果。
void addStatic(Mesh &mesh, Texture &texture, Transform transform) {
按值取一个Transform
,这意味着它被复制了,所以这个函数有它自己的实例。
std::make_shared<Static>(
mesh,
texture,
transform,
shader,
camera
));
Static::Static(Mesh &mesh, Texture &texture, Transform &transform, Shader &shader, Camera &camera)
:mesh(&mesh), texture(&texture), transform(&transform), shader(&shader), camera(&camera)
{}
将对局部变量的引用传递给Static::Static
,获取它的指针并存储该指针。addStatic
返回,本地Transform
被破坏,您最终获得指向Transform*
中空闲内存块的悬浮指针。
不确定你的其他指针,但你把所有的东西都作为参考,所以请检查,当它们将要被销毁时,其他指针也可能指向空闲空间。
By the way:
Static *statptr = stat.get();
statptr->Draw();
你不需要get()
指针。c++的智能指针的行为(几乎)像原始指针,所以
stat->Draw();
。
相关文章:
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 类方法 - 数据结构中 For 循环的运行时错误
- 使用本机 JNI 静态方法实现C++ Java 运行时错误
- C ++中的方法覆盖:是编译时还是运行时多态性?
- 是否有一种方法可以在运行时停止循环重复一次不止一次
- 是否有任何可能的方法将事件(自定义)附加到在运行时创建的对象?[C 构建器]
- 如何在 c++ 中修改运行时的方法?
- 在 OpenGL ES for Android 中运行时创建大型纹理的最有效方法
- 寻找一种在运行时检测 valgrind/memcheck 的方法,而无需包含 valgrind 标头
- 初始化期间的运行时类方法替换
- 是否有一种简单的方法可以在运行时在C 中创建/名称对象
- 在运行时创建TCOMBOBOX的更快方法
- 在运行时C 上覆盖相同的类方法
- 在运行时动态更新二进制文件(可执行文件)而不停止的任何类型的方法
- 在Visual Studio C 调试模式中捕获异常的最佳方法仅在从IDE运行时才会发生
- 是否有一种方法可以在运行时识别变量的const修饰符
- 在运行时按索引访问 std::tuple 元素的最佳方法
- 有没有更好的方法来处理将标识分配给层次结构中的类以供运行时使用
- 调用基于运行时逻辑的模板化C++方法
- C++11 在运行时不使用 switch 为元组编制索引的方法