Search code examples
c++pointersnullpointerexceptionshared-ptr

Read Access Violation while trying to use variables through shared pointers


This is for my university coursework.

I have a class called timestep that is going to be used as a typical timer in a game engine to calculate frame times, etc, and an application class.

I'm struggling to get my head around shared pointers, but am required to use one to access the timestep class from the application class. It doesn't throw up errors until the program is running, at which point it prints my "PRE TIMER" log to the console, and throws an exception after reaching timer->setStart(), flags the line start = ..... in the setStart method, and says **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();
        }
    }

}

Solution

  • Apparently, your timer in application.cpp is not pointing to any instance of Timestep, incurring the nullptr error. Explained simply, your shared pointer was not initialized.

    Assuming that you want a separate instance of Timestep for each instance of Application, maybe you could solve the issue by initializing your std::shared_ptr<Timestep> timer;

    Instead of

    std::shared_ptr<Timestep> timer;
    

    Try

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