c++ - 尝试通过共享指针使用变量时读取访问冲突

标签 c++ pointers nullpointerexception shared-ptr

这是我的大学类(class)。

我有一个名为timestep的类,它将被用作游戏引擎中的典型计时器以计算帧时间等,以及一个application类。

我正在努力寻找共享指针,但是必须使用一个指针来从timestep类访问application类。在程序运行之前,它不会引发错误,这时它将我的"PRE TIMER"日志打印到控制台,并在到达timer->setStart()之后引发异常,在start = .....方法中标记setStart行,并说**this** was nullptr

Timestep.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();
        }
    }

}

最佳答案

显然,您在application.cpp中的timer没有指向Timestep的任何实例,从而导致nullptr错误。简单地说,您的共享指针未初始化。

假设您需要为每个Application实例使用单独的Timestep实例,也许可以通过初始化std::shared_ptr<Timestep> timer;来解决此问题。

代替

std::shared_ptr<Timestep> timer;

尝试
std::shared_ptr<Timestep> timer(new Timestep());

关于c++ - 尝试通过共享指针使用变量时读取访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59621371/

相关文章:

c++ - 在 Windows 上列出 *.lib 中的函数

c++ - 虚函数调用始终比普通函数调用更快。为什么?

c - 在文件流中后退一位

java - 空检查后抛出空错误?

java - 为什么空指针异常不提供为空的表达式?

c# - P/Invoke问题(栈不平衡)

c++ - 访问 ".txt"文件中的信息并转到确定的行

c# - C++中指针和C#中引用类型的区别

C++ 帮助学生的指针

android - 读取文本文件并将其存储在数组中(Android 开发)