这是为我的大学课程准备的。
我有一个名为timestep的类,它将被用作游戏引擎中的一个典型计时器,用于计算帧时间等,还有一个application类。
我正在努力弄清楚共享指针,但我需要使用一个来从application类访问timestep类。在程序运行之前,它不会抛出错误,此时它会将我的"PRE TIMER"日志打印到控制台,并在到达timer->setStart()后抛出异常,在setStart方法中标记start = .....行,并指定**this** was nullptr。
Timestp.h:
#pragma once
#include <chrono>
namespace Engine {
class Timestep {
private:
std::chrono::high_resolution_clock::time_point start;
std::chrono::high_resolution_clock::time_point end;
public:
Timestep();
void setStart();
void setEnd();
float getTimeSeconds() const;
float GetTimeMilliSeconds() const;
};
}timestep.cpp:
#pragma once
#include "engine_pch.h"
#include "core/timestep.h"
namespace Engine {
Timestep::Timestep(){}
void Timestep::setStart() {
start = std::chrono::high_resolution_clock::now();
}
void Timestep::setEnd() {
end = std::chrono::high_resolution_clock::now();
}
float Timestep::getTimeSeconds() const {
std::chrono::duration<float> time = end - start;
return time.count();
}
float Timestep::GetTimeMilliSeconds() const {
std::chrono::duration<float, std::milli> time = end - start;
return time.count();
}
}application.cpp:
#include "engine_pch.h"
#include "core/application.h"
namespace Engine {
Application* Application::s_instance = nullptr;
std::shared_ptr<Timestep> timer;
Application::Application()
{
if (s_instance == nullptr)
{
s_instance = this;
}
log::log();
LOG_INFO("Logger init success");
}
Application::~Application()
{
}
void Application::run()
{
LOG_INFO("PRE TIMER");
timer->setStart();
LOG_INFO("POST TIMER");
while (s_instance) {
timer->setEnd();
float a = timer->getTimeSeconds();
LOG_INFO("Time since last frame is {0}", a);
timer->setStart();
}
}
}发布于 2020-01-07 10:27:46
显然,application.cpp中的timer没有指向Timestep的任何实例,从而导致nullptr错误。简单地解释一下,你的共享指针没有初始化。
假设您希望每个应用程序实例都有一个单独的Timestep实例,也许可以通过初始化std::shared_ptr<Timestep> timer;来解决这个问题
而不是
std::shared_ptr<Timestep> timer;试一试
std::shared_ptr<Timestep> timer(new Timestep());https://stackoverflow.com/questions/59621371
复制相似问题