【发布时间】:2016-11-05 06:34:40
【问题描述】:
为什么下面的代码会抛出
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;
}
静态头文件如下:
#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。
【问题讨论】:
-
shared_ptr似乎没有正确初始化。 -
你为什么要
get()指针?没必要。 -
@πάνταῥεῖ 我将包括将 shared_ptr 添加到向量的方法。
-
@Llewv 更好的是,为我们提供minimal reproducible example,它可以重现问题。
-
现在是
Static成员、构造函数和Draw方法。
标签: c++ shared-ptr runtimeexception